Select for update not working

删除回忆录丶 提交于 2019-12-25 14:48:12

问题


My following native query is not working:

Query createNativeQuery = entityManager.createNativeQuery(
   "select id from cscache where id=? for update ");

Environment Details:

  1. Mysql 5.6
  2. Jboss 5.1
  3. JPA 1.0

Error:

2014-12-12 10:20:14,581 WARN [org.hibernate.util.JDBCExceptionReporter]

SQL Error: 1064, SQLState: 42000 (http-0.0.0.0-8543-3:)

2014-12-12 10:20:14,581 ERROR [org.hibernate.util.JDBCExceptionReporter] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'limit 2' at line 1 (http-0.0.0.0-8543-3:)


回答1:


I haven't actually done a for update in hibernate, but I believe you can (and should?) do it on the Session or query object. Why not let hibernate do it instead of executing a native query? According to the documentation on locking (Chapter 5: Locking, you can set the lock mode on either the session or the query.

Cscache  cscache  = (Cscache )session.get( Cscache.class, id, LockOptions.UPGRADE );

Specifying the LockOptions should result in a SELECT ... FOR UPDATE being executed.




回答2:


For Update basically puts a lock on rows, to achieve the same using JPA you need to use Lock Modes. To set the lock, you can use EntityManager or TypeQuery and use LockModeType.PESSIMISTIC_WRITE.

Refer this article




回答3:


Not familiar with JPA specifically, but it appears you're not telling it what the value of ? is. Check out setParameter.



来源:https://stackoverflow.com/questions/27446755/select-for-update-not-working

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