Saturday, February 18, 2012

Persistence with JDBC

We will use the JDBC API to persist our User objects to the database.

First we need the MySQL JDBC adapter jar.

Update your ivy.xml to get the mysql-connector-java.jar, like this:

 <dependency org="mysql" name="mysql-connector-java" rev="5.1.18"/>  


Update your Eclipse classpath to include this jar.

We will create a Test class to demonstrate persistence with JDBC.

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

 package org.confucius;  


import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;

public class TestPersistence {

public static void main(String[] args) {
User user = new User();
user.setFirstName("John");
user.setLastName("Doe");

// Persist
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setUser("confucius");
dataSource.setPassword("changeit");
dataSource.setServerName("localhost");
dataSource.setPort(3306);
dataSource.setDatabaseName("confuciusDB");

try {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();

String sqlQuery = "insert into users value(\"" + user.getFirstName() + "\",\"" + user.getLastName() + "\")";
stmt.execute(sqlQuery);

stmt.close();
conn.close();

} catch (SQLException e) {
e.printStackTrace();
}
}
}




We create a DataSource, get a connection to the datasource, then execute a SQL query.

R-click on TestPersistence.java in Eclipse Navigator, then select Run As --> Java Application.

Then if you look at the users table in mysql, you will see the user persisted.

 mysql> select * from users;  
+-----------+----------+
| firstName | lastName |
+-----------+----------+
| John | Doe |
+-----------+----------+
1 row in set (0.00 sec)

No comments: