我正在尝试使用“for update”语句获取 mysql 数据库上某些行的锁定。为此,我在 Hibernate Transaction 的中间创建了一个 Criteria 并对其设置了锁定。
crit = session.createCriteria(AppIosVersion.class)
.add(Restrictions.eq("version", version))
.setLockMode(LockMode.PESSIMISTIC_WRITE);
使用 setLockMode 查询被正确发送到数据库,这是我在 mysql.log 中看到的:
133 Query SET autocommit=0
133 Query SET autocommit=1
133 Query SET autocommit=0
133 Query select this_.Version as Version1_5_0_, this_.EditTimeStamp as EditTime2_5_0_, this_.IsActive as IsActive3_5_0_ from AppAndroidVersion this_ where this_.Version='0.2' for update
130703 16:46:03 133 Query rollback
133 Query SET autocommit=1
问题是for update语句不允许获取锁,因为 hibernate beginTransaction() 不会成为mysql 中的START TRANSACTION。
我的休眠配置如下(我没有使用 Spring)。
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/Versions?autoReconnect=true</property>
<property name="connection.username">name</property>
<property name="connection.password">password</property>
<!-- Session properties -->
<!-- <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property> -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<property name="hibernate.connection.autocommit">false</property>
<!-- configuration pool via c3p0-->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.min_size">10</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.idle_test_period">180</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.timeout">600</property>
<property name="hibernate.c3p0.debugUnreturnedConnectionStackTraces">true</property>
<property name="hibernate.c3p0.unreturnedConnectionTimeout">180</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>