ps0604
ps0604

Reputation: 1071

EJB Entity: database row is automatically updated from Entity without save in EJB

The method loads a user entity bean from the database and returns it, but before doing that clears the password (setting it with null). The issue is that in the database itself the password is set with null, even though I don't have a merge or any other method that updates the entity. Any ideas?

public UserEntity loadFromDB (int userid) throws NotFoundException {

    UserEntity user = em.find(UserEntity.class, userid);
    if (user == null)
        throw new NotFoundException(); 

    user.setPassword(null);  

    return user;
} 

Upvotes: 1

Views: 880

Answers (1)

Avinash Singh
Avinash Singh

Reputation: 3797

It seems like the method loadFromDB is called within a transaction and so your Entity is attached and getting saved when transaction is closed.

Your DAO or service layer has transaction marked at class level and so the method is within a transaction.

If your method is part of transaction then it is basically adding below at start and end of transaction and it will commit updates to all the entities within transaction.

entityManager.getTransaction().begin();

// updates to entity

entityManager.getTransaction().commit(); //Saves all updates to DB

You can avoid it by doing that update outside your transaction in your view layer or by marking that method as not being part of transaction.

Mark your method as not part of transcation by adding

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)

Upvotes: 4

Related Questions