Uluk Biy
Uluk Biy

Reputation: 49215

JPA Best practice for managing entities in extended Persistence Context

I am using CDI conversation scoped, Seam managed extended persistence context (PC). This provides more fine-grained control over PC and avoids LIEs. I am using CDI Beans instead of EJB Beans. In a page, I retrieve list of entities and show them in a table. The selected entity record from the table is binded to the form and can be edited but not persisted until the "save" button is clicked. In this place the problem occurs, since all entities are managed the edited entities are also persisted when I try to flush/commit only one current entity in save action. What is the preferred best-practice approach to this kind of problems. Should I use middle POJO between the managed entity and the viewed/edited one? Should I detach then merge (before saving) the current in-progress entity? Any suggestions?

JPA 2.0, Hibernate 4.x
Seam 3 (Weld CDI, persistence, transaction, faces modules)
JSF 2.1
Java EE 6.

Upvotes: 4

Views: 1311

Answers (3)

Uluk Biy
Uluk Biy

Reputation: 49215

I am using Primefaces in front end and it was ajax submitting by default the changes made to the entity. The problem gone away after I have managed the Primefaces components.

Upvotes: 0

Xavier Portebois
Xavier Portebois

Reputation: 3504

We used a similar approach but with EJB3 beans and without the Seam persistence context. Nevertheless, maybe our experience could be useful to you.

The idea was :

  • use an extended PersistenceContext in the bean
  • make all methods without transaction - otherwise your entities will be committed after the call
  • make the save method the one with a transaction.

Detaching the entities will kill the benefit of giving entities to the front, as you will throw LazyException each time you're trying to access something that wasn't loaded. It would be quite the same as use some DTO.

Hope it helps!

Upvotes: 3

Tom Anderson
Tom Anderson

Reputation: 47253

If i understand correctly, then:

  1. Entity objects are displayed on a page
  2. The user can make changes to those objects
  3. The user can save an object to commit the changes to the database

I think the right approach here would be to detach the objects when they are edited, and then reattach them (by merging) when they are saved. That keeps the unsaved changes in memory only.

You don't actually need an extended persistence context for this, because any objects you need to keep between requests will be detached.

Upvotes: 2

Related Questions