简体   繁体   中英

How to modify column value? (JPA)

I need to change the value of a column using JPA query syntax(JPQL), how can i do it?

This is how i retrieve the row that i want to update:

@PersistenceContext
    private EntityManager em;

    public Role activateUser(long id) {
        Query query = em
                .createQuery("SELECT r.id FROM Role r WHERE r.id=" + id);
        Role tmpRole = (Role) query.getSingleResult();
        tmpRole.setAccountStatus(AccountStattus.ACTIVATED.toString());
        //How can i create query to save the changes here?)
        return tmpRole;
    }

Is there any other alternative to modify that row without retrieving it first?

What do you think is the best approach from the point of view of performance?

Use JPA in JPA way:

1) Load the entity, then it is attached to the current transaction. 2) Change the entity 3) Commit the transaction

The transaction handling can be done for example be @Transactional, but Java EE 5/6 has many other ways to do that.

@PersistenceContext
private EntityManager em;

//@Transactional - Not Java EE, anyway I keep it as notice that the method is invoked in a transaction.
public Role activateUser(long id) {
    Role role = em.find(Role.class, id);        
    role.setAccountStatus(AccountStattus.ACTIVATED.toString());
    //Thats all.
}

A

em.flush

after

tmpRole.setAccountStatus(AccountStattus.ACTIVATED.toString());

should be enough. As i recall, as long as a bean is managed by the EntityManager (which is the case here), all changes are automatically reflected.

If this doesn't work, then maybe try

tmpRole.setAccountStatus(AccountStattus.ACTIVATED.toString());
em.merge(tmpRole);

edit: BTW, for finding the role you can also write

em.find(Role.class, id);

if you have mapped the ID in the Role class correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM