Question

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.

Was it helpful?

Solution

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().

OTHER TIPS

If you don't use any transaction, CUD operatoins just will be done in business layer objects. You must begin a transaction before doing any CUD operation and commit (or flush???) it after the poeration done.

Try this:

entityManager.getTransaction().begin();
entityManager.persist(team);
entityManager.getTransaction().commit();

For more information: http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/transactions.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top