Introduction
If you are using Play! and a relational database you will be interested on using its play.db utilities. This package lets you configure a database connection and pool in the application.conf file.
If you want to integrate siena-jdbc with Play! you just need to provide a ConnectorManager to the JdbcPersistenceManager class. Implmenting a ConnectionManager is simple:
package utils.PlayConnectionManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import play.db.DB;
import siena.SienaException;
import siena.jdbc.ConnectionManager;
public class PlayConnectionManager implements ConnectionManager {
public Connection getConnection() {
return DB.getConnection();
}
public void init(Properties properties) {
}
public void beginTransaction(int isolationLevel) {
try {
Connection c = getConnection();
c.setAutoCommit(false);
c.setTransactionIsolation(isolationLevel);
} catch (SQLException e) {
throw new SienaException(e);
}
}
public void commitTransaction() {
try {
Connection c = getConnection();
c.commit();
} catch (SQLException e) {
throw new SienaException(e);
}
}
public void rollbackTransaction() {
try {
Connection c = getConnection();
c.rollback();
} catch (SQLException e) {
throw new SienaException(e);
}
}
public void closeConnection() {
try {
getConnection().close();
} catch (SQLException e) {
throw new SienaException(e);
}
}
}Usually you will configure Siena using a siena.properties file. But with Play! is better to create a Job that runs OnApplicationStart. Example
import models.User;
import play.jobs.Job;
import play.jobs.OnApplicationStart;
import siena.PersistenceManagerFactory;
import siena.jdbc.JdbcPersistenceManager;
import utils.PlayConnectionManager;
@OnApplicationStart
public class ConfigureDatabase extends Job {
@Override
public void doJob() {
JdbcPersistenceManager pm = new JdbcPersistenceManager(new PlayConnectionManager(), null);
try {
PersistenceManagerFactory.install(pm, User.class);
} catch(Exception e) {
e.printStackTrace();
}
}
}Where "models.User" is one class of your "models" package. With this code every class in the same package will use that PersistenceManager.
And that's all. Now you have Siena integrated into Play!. Play! will care of your connection management and siena will provide you the persistence layer :)
AMAZING!!