CDI Injection in Hibernate Entities

inject entity manager cdi
cdi jpa
cdi tutorial
persistencecontext
hibernate baeldung
java se cdi
jax-rs inject entitymanager
jpa entitymanager example with annotation

We are using CDI(JSR 299) in our application (JSF2/Seam3.0/Hibernate 3.5.6/GlassFish 3.1.1)

While we are unable to inject resources(Helper POJOs) in our managed beans using @Inject, we cannot do the same in our Hibernate Entity classes.

We have a base entity class(@MappedSuperclass) that all entity objects derive from. CDI injection fails in both classes.

@MappedSuperclass
public class BaseBusinessObject implements Serializable
{     
    @Inject
    private TestClass testClass; //FAILS
}


@Entity
@NamedQueries({ @NamedQuery(name = "Account.findAll", query = "SELECT b FROM Account b") })
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Account extends BaseBusinessObject
{
    @Inject
    private TestClass testClass; //FAILS

}

It seems like it may be a limitation with CDI. Can anyone confirm whether CDI works with Hibernate entities.

Any inputs would be appreciated.

Thanks & Regards

I don't really know CDI but i really don't think it is possible. Event if we could, in many cases, it would probably lead to a really bad design.

Do you wish CDI to create a single hibernate entity for the whole application, and inject your helpers/services/whatever in it? Or do you wish CDI to inject stuff in any entity you create with "new Entity()"?


Edit: Generally a Date Time utils doesn't hold any state and doesn't need any CDI injected stuff, so why not make all the methods static like what we find in apache commons DateUtils?

If your Date Time utils need a state, make it a singleton (but take care with concurrency issues).

If your Date Time utils needs to call other CDI beans (so it can't be static) then you'd rather make it a singleton, and inject on the singleton the other CDI beans.

But it's a bad idea. This may lead to have a business layer that manage entities that call back the business layer or something like that, with some circular dependency problems and a tight coupling between your entities and your business layer.

CDI Injection in Hibernate Entities, For example, if a property of your entity is annotated @NotNull , its columns will be package org.hibernate.validator.referenceguide.chapter10.cdi.injection;  The crux of the matter of any CDI-based JPA application is the creation of an injectable entity manager. It’s worth noting that regardless of the approach that we use to get the manager, once it becomes an injectable Java EE resource, the entirety of the examples shown in the rest of the post are equally valid.

It's a bad practice to systematically use JPA entity as CDI bean (but it's possible if you want to). That's mainly because of the 'C' of CDI : Context.

All CDI implementations use proxy mechanism to handle injection of a bean of a given scope in a bean of a different scope. And as most JPA implementation use also proxy to handle some mechanism (Lazy Loading for instance) you will finished with a bunch of proxies in your class with different life cycles : a mess !

Weld documentation as even a waning about this issue : Chapter 5. Scopes and Contexts

However it could be useful in some case to expose an entity as CDI bean, but you'd prefer to use a producer to do so :

@Produces
@Named
@RequestScoped
private MyEntity produceMyEntity()
{
     return new MyEntity(); //or any JPA lookup you'll need
}

This way is the most convenient but you should be very careful when mixing managed entities and CDI

Chapter 10. Integrating with other frameworks, Basically, CDI is an annotation-driven injection framework that will be used by Producer methods to create a MySQLDatabase-bound Entity Manager: <​property name="hibernate.hbm2ddl.auto" value="create-drop"  WFLY-8557 CDI injection in entity listeners failing in WAR contained in EAR. Closed

you can firing CDI Events in a JPA Entity or EntityListener. and inject the TestClass to the class which contains Observes method. look at following link for more information: http://blogs.bytecode.com.au/glen/2014/01/09/firing-cdi-events-from-a-jpa-entitylistener.html

you can also access to the BeanManager as follow( instead JNDI lookup)

CDI.Current().getBeanManager()

CDI and JPA tutorial, That example project uses Weld as the CDI container, Hibernate ORM With the producers in place, we can inject an entity manager into CDI  Seam3 Persistence Module, using CDI to inject entity manager in Java SE environment, My intention is to create an example using CDI in java SE environment and inject an entity manager. This way it would be easier to test any project's DAO layer, and using maven, this layer could be constructed in an isolated single project.

Testing CDI Beans and the Persistence Layer Under Java SE, I @Inject some CDI bean (@RequestScoped in my case but happens for other scopes, too) into the I do have JPA entities annotated with @EntityListeners. I @Inject mkouba added the area/hibernate-orm label on Feb 2. Which means you can have some entities defined in .hbm.xml and some others through @Entity annotations. Injecting Hibernate Session and SessionFactory : You can inject a org.hibernate.Session and org.hibernate.SessionFactory directly into your EJBs just as you can do with EntityManagers and EntityManagerFactorys.

@Inject Injection into EntityListener not working · Issue #6948 , CDI is the Java standard for dependency injection (DI) and interception CDI is to Spring and Guice what JPA is to Hibernate, and Toplink. JBoss Seam 3 is built on top of CDI and has at it's core concept the notion of conversation and unit of work. For an application-managed entity manager the persistence context is created when the entity manager is created and kept until the entity manager is closed. In an extended persistence context,

CDI Dependency Injection, Apache DeltaSpike project provides a comprehensive set of CDI extensions each its JDBC driver and the Hibernate dependencies should also be added: To be able to access the entity manager instance via injection, we  Java example of hibernate validator CDI to inject default Java bean validation classes implementations e.g. javax.validation.ValidatorFactory and javax.validation.Validator with hibernate-validator-cdi dependency. Also learn to inject specialized validator if application has multiple validator implementations like org.hibernate.validator.cdi.HibernateValidator.

Comments
  • Hi Sebastien, Thank you for your response. We use multiple Hibernate entities but they all derive (basic properties like creation date time) from a base Entity class. We are trying to inject a Date Time Utility class in this base class to get Entity creation time and this injection fails.
  • Hi Antoine, Thank you for your response. We are not trying to produce an Entity using CDI. The entity is produced using new() operator. However, as specified to Sebastien, all our entities derive (basic properties like creation date time) from a base Entity class. We are trying to inject a Date Time Utility class in this base class to get Entity creation time and this injection point is failing. Please let me know if you need any more information.