How to use JPA lock?

一笑奈何 提交于 2019-12-13 05:56:03

问题


Yes, I know maybe the question is very wide, but I don't understand how the JPA lock works.

I will put an example about how I'm using it:

public Account deposit(int id, double quantity) {
    Account a = super.find(id);
    if (a == null) {
        return null;
    }
    try {
        em.lock(a, LockModeType.PESSIMISTIC_WRITE);
        a.setSaldo(a.getSaldo() + quantity);

        LOG.log(Level.INFO, " //\u00a0 Se ha depositado, saldo :{0}", a.getSaldo());
    } catch (Exception oe) {
        LOG.log(Level.INFO, oe.getMessage());
    }
    return a;
}

And you are thinking "so?"

Well, when I apply the lock the next statement will update the record without a "merge" instruction, but when the lock is finished? , this means I can continue making changes (ie a.setFOO(bar)) until the return statement is reached and will commit the changes? or do I need to make another lock?

AFAIK the pessimistic write lock will make a SELECT... FOR UPDATE , but since I don't have a "transaction.begin()" I have no idea about the scope of the lock. I'm injecting the Entity manager via

@PersistenceContext(unitName = "PruebaConcurrenciaPU")
private EntityManager em; 

thanks!

来源:https://stackoverflow.com/questions/38127641/how-to-use-jpa-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!