mysql和jpa,JPA和MySQL事务隔离级别

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!

解决方案

You need to set it at the connection level, get the session from the entitymanager and do this:

org.hibernate.Session session = (Session)entityManager.getDelegate();

Connection connection = session.connection();

connection.setTransactionIsolation(Connection.READ_UNCOMMITTED);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值