-
Notifications
You must be signed in to change notification settings - Fork 11
Entities
In Seam 2, it is quite common to use JPA entities as Seam managed objects. Take the User entity from the booking application as an example. Such entity is instantiated by Seam and stored in the session context. Its values are bound to a form in a JSF page using EL expressions and filled by an application user. Finally, the managed object is passed to the EntityManager
and persisted in the database.
Since Seam 2 stores direct references to bean objects in its contexts, the approach above works fine for non-intercepted entities (which entities usually are).
CDI uses different memory model (TODO write a chapter on this difference). Everytime an application code accesses a reference to a CDI-managed bean stored in a normal context, it actually accesses a dynamic client proxy. Since proxy classes are different from the original classes of the entity, they cannot be used in the persist()
method of the EntityManager. Therefore, never use entities as CDI managed beans.
Although this may seem like a major limitation, it is not the case. Most of the time, there is not need for JPA entities to support dependency injection nor they need to be interceptor. The only services really useful to entities is storing them in a context. CDI supports this in form of a producer field or method. The common approach is to use a stateful manager object for instantiating and holding the reference to a scoped entity. See the Registrar component of the Seam 3 booking application as an example.