Search code examples
javasqljpajakarta-eejava-ee-6

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?


Solution

  • 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.
    }