java 如何查看Hibernate发出的用于设置事务级别和自动提交的SQL查询

piv4azn7  于 2023-04-10  发布在  Java
关注(0)|答案(2)|浏览(158)

在我的MySQL服务器上,在常规日志中,我看到大量的日志,看起来像:

2023-03-31T09:31:23.208-07:00   2023-03-31T16:31:23.208345Z37028 Query SET autocommit=0
2023-03-31T09:31:23.211-07:00   2023-03-31T16:31:23.211201Z36956 Query set session transaction read write
2023-03-31T09:31:23.211-07:00   2023-03-31T16:31:23.211807Z36957 Query /* dynamic native SQL query */ select now() /*app health check*/
2023-03-31T09:31:23.255-07:00   2023-03-31T16:31:23.255990Z36995 Query set session transaction read write
2023-03-31T09:31:23.273-07:00   2023-03-31T16:31:23.273013Z36957 Query set session transaction read write
2023-03-31T09:31:23.276-07:00   2023-03-31T16:31:23.276323Z36956 Query SET autocommit=0
2023-03-31T09:31:23.320-07:00   2023-03-31T16:31:23.320214Z36995 Query SET autocommit=0
2023-03-31T09:31:23.334-07:00   2023-03-31T16:31:23.334801Z36957 Query SET autocommit=0
2023-03-31T09:31:23.461-07:00   2023-03-31T16:31:23.461897Z37056 Query rollback

我希望在客户端日志中看到它们。我的Java非常生疏,所以请耐心等待。如果它有帮助,我问的问题看起来非常类似于this one,尽管那里接受的答案实际上也没有最终为我工作(这是一个单独的问题):/
我有一个YAML文件,并尝试启用以下内容:

logging:
  levels:
  - path: org.hibernate
    value: trace
  - path: org.hibernate.SQL
    value: debug
  - path: org.jooq
    value: trace
  - path: com.amazonaws
    value: debug
  - path: com.zaxxer
    value: debug
  - path: com.mysql
    value: debug
  - path: org.hibernate.engine.transaction.internal.TransactionImpl
    value: debug
  - path: com.mysql.clusterj.core.TransactionImpl
    value: debug
  - path: org.hibernate.jpa.internal.TransactionImpl
    value: debug
toe95027

toe950271#

Hibernate不发送这些查询,而是JDBC驱动程序发送它们。相关的JDBC API是java.sql.Connection.setAutoCommit(),在容器环境中,该方法通常由连接池调用。

pn9klfpd

pn9klfpd2#

Hibernate的配置是这样的,以启用自动提交:
<property name="connection.autocommit">true</property>
交易级别可以在代码中设置

EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("sampleUnit");
EntityManager em1 = emFactory.createEntityManager();
EntityTransaction t1 = em1.getTransaction();
t1.begin();
try {
  Query query = em1.createQuery("SELECT p FROM Product p WHERE name = :name");
  query.setParameter("name", "cherry");
  List<Product> products = query.getResultList();
  System.out.println("Got product size: "+products.size());
} finally {
  t1.rollback();
}

相关问题