Saturday, February 18, 2012

Persistence - Database setup

Let us see how to persist objects to a database.

We will create a User.java class, and persist its instances.

In your /src/org/confucius, create a class User.java, like this:

 package org.confucius;  

public class User {
private String firstName;
private String lastName;

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return firstName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getLastName() {
return lastName;
}
}



Let us create a database to persist this class to.

Open your MySql command line client, and give the following command to create the database 'confuciusDB':

 mysql> create database confuciusDB;  
Query OK, 1 row affected (0.00 sec)


Create a table 'users' using the following commands:

 mysql> use confuciusDB;  
Database changed

mysql> create table users (firstName VARCHAR(32), lastName VARCHAR(32));
Query OK, 0 rows affected (0.10 sec)


Create a user 'confucius' with password 'changeit', and grant all permissions.

 mysql> create user 'confucius'@'localhost' IDENTIFIED BY 'changeit';  
Query OK, 0 rows affected (0.06 sec)

mysql> grant all privileges on *.* to 'confucius'@'localhost';
Query OK, 0 rows affected (0.00 sec)


We are all set to persist User instances.