Search code examples
jsfjpacdi

Injecting Entity Class in CDI backing bean


I would like to know which is good practice. For example, I have Person pojo for Entity Class,PersonService EJB stateless session bean for persisting Person class and indexBean(CDI request Scope bean)for binding with JSF to create Person class.
Is it good to create new Person Object in indexBean instead of using @Inject?
If not, could you show me how should i design for this scenario? Thanks.


Solution

  • According to the CDI documentation of weld, you should not inject Entity beans:

    According to this definition, JPA entities are technically managed beans. However, entities have their own special lifecycle, state and identity model and are usually instantiated by JPA or using new. Therefore we don’t recommend directly injecting an entity class. We especially recommend against assigning a scope other than @Dependent to an entity class, since JPA is not able to persist injected CDI proxies.

    You can find further information here.

    You shoud create a new Person object / or load it from Database (by your PersonService) in your indexBean, depending on your usecase. Also the persistence of the Person entity will finally be done by your PersonService.