Auxiliary Tools :: Hibernate CDI Standalone Example

 

Based on https://www.sitepoint.com/cdi-weld-inject-jpa-hibernate-entity-managers/ with my changes and extensions: project structure, multiple entity producer, injectable logger…

Environment: Weld 2.3.3.Final, J2SE 8, Hibernate 5.1.8.Final, h2-1.4.196.

Project structure:

 

Creating an Injectable Entity Manager

Using the @PersistentContext Annotation

The most painless way, which only works with a Java EE application server is the @PersistenceContext annotation. This methodology binds a persistence context (and a persistence unit) to an entity manager, and the manager’s lifecycle is entirely managed by the container (aka a container-managed entity manager). This approach can be implemented by using a custom qualifier like this:

With that code in place, a simple DAO class that takes the entity manager in the constructor can be defined as follows:

 

Non-managed Entity Manager (our example)

Usage:

 

Data Access
This layer is made up of a generic interface and a implementation:

Implementation:

 

Entities Producer

UserDao declares a dependency to the domain class that models user entities. Here are the custom qualifier, annotation, enum, and the producer required for injecting of many entities:

Entities names:

Producer:

 

Application Layer

 

Injectable Resources

BufferedReaderProducer:

Logger:

 

TODO
Implementation of Address.java entity.

 

Source Download
cdi-hibernate-01.zip

 

Leave a Reply