简体   繁体   English

如何修改列值? (JPA)

[英]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? 我需要使用JPA查询语法(JPQL)更改列的值,我该怎么做?

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: 以JPA方式使用JPA:

1) Load the entity, then it is attached to the current transaction. 1)加载实体,然后将其附加到当前事务。 2) Change the entity 3) Commit the transaction 2)更改实体3)提交事务

The transaction handling can be done for example be @Transactional, but Java EE 5/6 has many other ways to do that. 事务处理可以是例如@Transactional,但Java EE 5/6还有许多其他方法可以做到这一点。

@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. 我记得,只要一个bean由EntityManager管理(这里就是这种情况),所有的更改都会自动反映出来。

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 编辑:BTW,找到你也可以写的角色

em.find(Role.class, id);

if you have mapped the ID in the Role class correctly. 如果您已正确映射Role类中的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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