代码之家  ›  专栏  ›  技术社区  ›  armandino

JPA和MySQL事务隔离级别

  •  3
  • armandino  · 技术社区  · 15 年前

    我有一个原生查询,它在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(...);
        }
    

    此查询导致死锁:当它从 t2 insert .. select ,另一个进程尝试在 t2型 .

    t2型 插入。。选择 并希望将事务隔离级别设置为 READ_UNCOMMITTED .

    我该如何在JPA中设置它?


    所以我最终为这个例子创建了一个常规的SQL连接,因为在我看来这是最简单的选择。谢谢大家!

    3 回复  |  直到 15 年前
        1
  •  4
  •   Guillaume    15 年前

    您需要在连接级别设置它,从entitymanager获取会话并执行以下操作:

    org.hibernate.Session session = (Session)entityManager.getDelegate();
    Connection connection = session.connection();
    connection.setTransactionIsolation(Connection.READ_UNCOMMITTED);
    
        2
  •  3
  •   DataNucleus    15 年前

    在JPA中你不需要。JDO是唯一支持设置txn隔离的标准。显然,使用特定的实现方法可以允许这样做,但是之后您就变得不可移植了

        3
  •  0
  •   OpenSource    15 年前

    由于您使用的是BMT,因此可以使用数据源执行以下操作以获取连接。

    DataSource source = (javax.sql.DataSource) jndiCntxt.lookup("java:comp/env/jdbc/myds");
    Connection con = source.getConnection( );
    con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);