JPA和MySQL事务隔离级别
我有一个本机查询,可以批量插入 MySQL 数据库:
String sql = "insert into t1 (a, b) select x, y from t2 where x = 'foo'";
EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
int rowCount = entityManager.createNativeQuery(sql).executeUpdate();
tx.commit();
return rowCount;
}
catch(Exception ex) {
tx.rollback();
log.error(...);
}
此查询会导致死锁:当它使用 insert .. select
从 t2
读取时,另一个进程尝试在 t2
中插入一行。
在执行 insert .. select
时,我不关心从 t2
读取的一致性,并且希望将事务隔离级别设置为 READ_UNCOMMITTED。
我该如何在 JPA 中设置它?
更新
所以我最终为这种情况创建了一个常规 SQL 连接,因为在我看来这是最简单的选择。谢谢大家!
I have a native query that does a batch insert into a MySQL database:
String sql = "insert into t1 (a, b) select x, y from t2 where x = 'foo'";
EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
int rowCount = entityManager.createNativeQuery(sql).executeUpdate();
tx.commit();
return rowCount;
}
catch(Exception ex) {
tx.rollback();
log.error(...);
}
This query causes a deadlock: while it reads from t2
with insert .. select
, another process tries to insert a row into t2
.
I don't care about the consistency of reads from t2
when doing an insert .. select
and want to set the transaction isolation level to READ_UNCOMMITTED.
How do I go about setting it in JPA?
Update
So I ended up creating a regular SQL connection for this case as it seemed to me the simplest option. Thanks everyone!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在连接级别设置它,从实体管理器获取会话并执行以下操作:
You need to set it at the connection level, get the session from the entitymanager and do this:
在 JPA 中则不然。 JDO 是唯一支持设置 txn 隔离的标准。显然,采用特定的实现方法可以允许它,但随后你就变得不可移植
In JPA you don't. JDO is the only standard that supports setting txn isolation. Obviously going for particular implementations methods can allow it, but then you become non-portable
由于您使用的是 BMT,因此您可以使用数据源执行以下操作来获取连接。
并设置iso。等级。
Since you are using BMT, you can do the following using a datasource to get the connection.
and set the iso. level.