Skip to content

Guice Persist

Zsolt Herpai edited this page Feb 20, 2015 · 5 revisions

Extension library

FluentJdbc has an extension library to support integration with Guice Persist.

<dependency>
    <groupId>org.codejargon</groupId>
    <artifactId>fluentjdbc-guice-persist</artifactId>
    <version>0.9.2</version>
</dependency>

Note: version should match FluentJdbc's version

Modules

It implements modules to support:

  • Standalone FluentJdbc - including transaction management
  • Seamless integration to Guice Persist with JPA (JpaPersistModule)

Both modules will set / override the ConnectionProvider of FluentJdbc, and bind FluentJdbc and Query instances to Guice container and support transaction management with Guice Persist's @Transactional annotation.

Example of usage after configuration:

@Inject
private Query query;

@Transactional
public void updateSomething() {
    query.update(someSqlQuery).....
}

Standalone FluentJdbc with GuicePersist transaction management

Needs configuration of FluentJdbc (through FluentJdbcBuilder), and a DataSource instance (preferably one based on a pool).

DataSource dataSource = ... 
FluentJdbcBuilder builder = new FluentJdbcBuilder()...
StandaloneFluentJdbcModule fluentJdbcModule = new StandaloneFluentJdbcModule(builder, dataSource);
install(fluentJdbcModule);

Integration with Guice Persist JpaPersistModule

JpaFluentJdbcModule can be used in conjunction with JpaPersistModule to integrate seamlessly with JPA (including transaction management). The module will override the ConnectionProvider with an own implementation that extracts Connections from the JPA EntityManager.

Extraction of Connections from an EntityManager requires the use of vendor specific API. The modules also needs configuration of FluentJdbc (through FluentJdbcBuilder)

FluentJdbcBuilder fluentJdbcBuilder = new FluentJdbcBuilder()... 
JpaConnectionExtractor extractor = ... 
JpaFluentJdbcModule fluentJdbcModule = new JpaFluentJdbcModule(fluentJdbcBuilder, extractor);
install(..., jpaPersistModule, fluentJdbcModule, ...)

Examples for JpaConnectionExtractor:

EclipseLink
JpaConnectionExtractor extractor = entityManager -> {
    return entityManager.unwrap(java.sql.Connection.class);
}
Hibernate 4.x
JpaConnectionExtractor extractor = entityManager -> {
    Session session = entityManager.unwrap(Session.class);
    SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
    return sfi.getConnectionProvider().getConnection();
}