You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The steps below describe how to use Pippo with JPA/Hibernate + Guice Persist
In this example
the database is H2
a HTTP Filter manage EntityManager during HTTP request
using Pippo Controllers
Let's now configure JPA/Hibernate + Guice Persist for use in our application.
Initially we need to define some dependencies in pom.xml
<properties>
<hibernate.version>5.2.1.Final</hibernate.version>
<google.guice.version>4.0</google.guice.version>
</properties>
<dependencies>
<!-- Engine to Pippo convert to Json -->
<dependency>
<groupId>ro.pippo</groupId>
<artifactId>pippo-gson</artifactId>
<version>${pippo.version}</version>
</dependency>
<!-- In this example we will work with Controllers -->
<dependency>
<groupId>ro.pippo</groupId>
<artifactId>pippo-controller</artifactId>
<version>${pippo.version}</version>
</dependency>
<!-- Our controllers will be able to inject Guice components -->
<dependency>
<groupId>ro.pippo</groupId>
<artifactId>pippo-guice</artifactId>
<version>${pippo.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Guice extension to manager the EntityManager lifecycle -->
<dependency>
<groupId>com.google.inject.extensions</groupId>
<artifactId>guice-persist</artifactId>
<version>${google.guice.version}</version>
</dependency>
<!-- H2 database driver -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.194</version>
</dependency>
</dependencies>
Now we need to set up a JPA peristence unit in /src/main/java/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistenceversion="2.1"xmlns="http://xmlns.jcp.org/xml/ns/persistence"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unitname="pippojpaPersistenceUnit"transaction-type="RESOURCE_LOCAL">
<properties>
<!-- Oracle --><!-- <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle12cDialect" /> <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>--><!-- Postgres --><!-- <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL95Dialect" /> <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>--><!-- H2 -->
<propertyname="hibernate.dialect"value="org.hibernate.dialect.H2Dialect" />
<propertyname="javax.persistence.jdbc.driver"value="org.h2.Driver"/>
<!-- Hibernate 5.2: none (default value), create-only, drop, create, create-drop, validate, and update -->
<propertyname="hibernate.hbm2ddl.auto"value="create" />
<!-- <property name="hibernate.hbm2ddl.import_files" value="importInicial.sql,import.sql" />-->
<propertyname="javax.persistence.jdbc.url"value="jdbc:h2:./db/h2/pippojpa/pippojpa;AUTO_SERVER=true" />
<propertyname="javax.persistence.jdbc.user"value="sa"/>
<propertyname="javax.persistence.jdbc.password"value="sa"/>
<propertyname="hibernate.show_sql"value="false" />
<propertyname="hibernate.use_sql_comments"value="true" />
<propertyname="hibernate.format_sql"value="false" />
<!-- AUTO : The Session is sometimes flushed before query execution --><!-- COMMIT: The Session is only flushed prior to a transaction commit -->
<propertyname="org.hibernate.flushMode"value="COMMIT"/> <!-- default: AUTO -->
<propertyname="hibernate.connection.autocommit"value="false"/> <!-- default is false -->
<propertyname="hibernate.connection.pool_size"value="3"/>
<propertyname="hibernate.enable_lazy_load_no_trans"value="false"/> <!-- default is false -->
</properties>
</persistence-unit>
</persistence>
We will need a filter to enable the HTTP Request unit of work and to have guice-persist manage the lifecycle of active units of work. In other words: to manage the EntityManager during the HTTP request lifecycle.
For Guice to manage the EntityManager it needs to know the persistence unit to create the instances in the dependency injections.
Let's then create a Guice Module pointing to our persistence unit. It's very simple.
CityDAO.java Here is a very simple implementation just to demonstrate this use case.
importjava.io.Serializable;
importjava.util.List;
importjavax.persistence.EntityManager;
importjavax.persistence.TypedQuery;
importcom.google.inject.Inject;
importcom.google.inject.Provider;
importcom.google.inject.persist.Transactional;
publicclassCityDAO {
@InjectprivateProvider<EntityManager> emProvider;
privateEntityManagergetEntityManager() {
returnemProvider.get();
}
// Transaction is not requiredpublicList<City> getAll() {
finalStringqlString = "FROM " + City.class.getName();
TypedQuery<City> query = getEntityManager().createQuery(qlString, City.class);
returnquery.getResultList();
}
// Transaction is not requiredpublicCitygetById(Serializableid) {
returngetEntityManager().find(City.class, id);
}
@TransactionalpublicCitysave(Citycity) {
Cityentity = persist(city);
getEntityManager().flush();
returnentity;
}
@TransactionalpublicvoiddeleteById(Serializableid) {
Cityentity = getEntityManager().find(City.class, id);
// Case of attached entity - simply remove itif (getEntityManager().contains(entity)) {
getEntityManager().remove(entity);
} else {
// Case of unattached entity, first it is necessary to perform// a merge, before doing the removeentity = getEntityManager().merge(entity);
getEntityManager().remove(entity);
}
}
private <T> Tpersist(Tentity) {
// Case of new, non-persisted entityif (extractId(entity) == null) {
getEntityManager().persist(entity);
} elseif (!getEntityManager().contains(entity)) {
// In the case of an attached entity, we do nothing (it// will be persisted automatically on synchronisation)// But... in the case of an unattached, but persisted entity// we perform a merge to re-attach and persist itentity = getEntityManager().merge(entity);
}
returnentity;
}
privateObjectextractId(Objectentity) {
returngetEntityManager().getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(entity);
}
}
Finally we need to make final configurations in the PippoApplication.onInit()
importcom.google.inject.Guice;
importcom.google.inject.Injector;
importcom.google.inject.Module;
importcom.google.inject.persist.PersistService;
importro.pippo.controller.ControllerApplication;
importro.pippo.guice.GuiceControllerFactory;
publicclassPippoApplicationextendsControllerApplication {
@OverrideprotectedvoidonInit() {
// http://docs.jboss.org/hibernate/orm/5.2/topical/html_single/logging/Logging.htmlSystem.setProperty("org.jboss.logging.provider", "slf4j"); // Required for Hibernate when using slf4jModuleguiceModule = newJPAGuiceModule();
Injectorinjector = Guice.createInjector(guiceModule); // create guice injectorsetControllerFactory(newGuiceControllerFactory(injector)); // register GuiceControllerFactoryPersistServiceservice = injector.getInstance(PersistService.class);
service.start(); // starts the persistence unit// This filter should be applied only to contexts that may require the EntityManagerANY("/pages/.*", PersistFilter.buildBegin(injector));
addControllers(CityController.class);
// Here your other controllers, routes, configurations, ...// Cleanup - It should actually be the last call of the onInit() methodANY("/pages/.*", PersistFilter.buildEnd()).runAsFinally();
}
}
Here we have Pippo fully configured to work with Hibernate / JPA, including with the automatic management of resources allocated by EntityManager through the HTTP filter created.
Launch the application... Lets test... Let's use cURL to make requests.
$ # getting all cities, must be empty
$ curl http://localhost:8338/pages/city/getAll
[]
$ # inserting three cities and getting the IDs
$ curl -X POST http://localhost:8338/pages/city/save -H 'content-type: multipart/form-data' -F name=city1
{"id":1,"name":"city1"}
$ curl -X POST http://localhost:8338/pages/city/save -H 'content-type: multipart/form-data' -F name=city2
{"id":2,"name":"city2"}
$ curl -X POST http://localhost:8338/pages/city/save -H 'content-type: multipart/form-data' -F name=city3
{"id":3,"name":"city3"}
$ # getting all cities (there must be three)
$ curl http://localhost:8338/pages/city/getAll
[{"id":1,"name":"city1"},{"id":2,"name":"city2"},{"id":3,"name":"city3"}]
$ # query the city with ID 1
$ curl http://localhost:8338/pages/city/get/1
{"id":1,"name":"city1"}
$ # delete the city with ID 2
$ curl -X DELETE http://localhost:8338/pages/city/delete/2
City with id 2 was deleted
$ # getting all cities, but the city with ID 2 no longer available
$ curl http://localhost:8338/pages/city/getAll
[{"id":1,"name":"city1"},{"id":3,"name":"city3"}]
$ # done!
Activity
mhagnumdw commentedon Aug 3, 2018
I use only JPA/Hibernate + Guice Persist. If you want I can write about it later.
mhagnumdw commentedon Aug 13, 2018
The steps below describe how to use Pippo with JPA/Hibernate + Guice Persist
In this example
Let's now configure JPA/Hibernate + Guice Persist for use in our application.
Initially we need to define some dependencies in
pom.xmlNow we need to set up a JPA peristence unit in /src/main/java/META-INF/
persistence.xmlWe will need a filter to enable the HTTP Request unit of work and to have guice-persist manage the lifecycle of active units of work. In other words: to manage the EntityManager during the HTTP request lifecycle.
For Guice to manage the EntityManager it needs to know the persistence unit to create the instances in the dependency injections.
Let's then create a Guice Module pointing to our persistence unit. It's very simple.
Let's now build a JPA entity, a DAO, and a controller to test our configuration.
Below is a simple JPA entity called
City.CityDAO.javaHere is a very simple implementation just to demonstrate this use case.
CityController.javaFinally we need to make final configurations in the PippoApplication.onInit()
Here we have Pippo fully configured to work with Hibernate / JPA, including with the automatic management of resources allocated by EntityManager through the HTTP filter created.
Launch the application... Lets test... Let's use cURL to make requests.
mhagnumdw commentedon Aug 13, 2018
⬆️
@decebals, let me know about any improvement. I put a complete example. Maybe you want to reduce something.
decebals commentedon Sep 22, 2018
@mhagnumdw It's OK. Thanks!