I have a Seam 3/JBoss/Hibernate project with a @ConversationScoped
bean. This bean manages the creation/editing of an @Entity
. I would like to be able to save any changes made to the Entity and keep the User on the current page.
@Named
@Stateful
@ConversationScoped
public class TeamManagementBean implements Serializable {
@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
@Inject
Conversation conversation;
@Inject
FlushModeManager flushModeManager;
protected Team team;
@Inject
@CurrentUser
private User currentAccount;
@Begin
public void loadTeam(Team team) {
if(conversation.isTransient()) conversation.begin();
flushModeManager.setFlushModeType(FlushModeType.MANUAL);
this.team = team;
}
public void save() {
if(team.isUnsaved()) entityManager.persist(team);
entityManager.flush();
}
When save()
is called, the Entity in the conversation is updated (that is, the changes appear in the Conversation and on the web page. However, the data doesn't get written to the database, even if I end the conversation.
On another part of the site, I was able to update an Entity in the database by having a faces-config.xml
redirect to a different page when the save()
method was called. But I'd like to keep the User on the same page when saving this Entity.
It depends on how the entity is loaded when it is passed to loadTeam()
; this should be done by using entityManager.find()
or by using a query. Hibernate will only update the database if the entity belongs to the current persistence context, which you can check by using entityManager.contains()
, e.g.:
public void save() {
...
System.out.println("contains(): " + entityManager.contains(team));
entityManager.flush();
}
If possible, the call to System.out.println()
should of course be replaced by using your logging facilities.
If the entity is detached before being passed to loadTeam()
, you will have to use entityManager.merge()
.