Problem

How do you determine what SQL query is being executed by Hibernate? How can you see the Hibernate’ internal workings? How do you enable logging to troubleshoot complex issues related to Hibernate?

Solution

You have to enable Hibernate logging in the Hibernate configuration. Hibernate uses Simple Logging Facade for Java (SLF4J) to log various system events. SLF4J, which is distributed as a free software license, abstracts the actual logging framework that an application uses. SLF4J can direct your logging output to several logging frameworks:

  • NOP: Null logger implementation
  • Simple: A logging antiframework that is very simple to use and attempts to solve every logging problem in one package
  • Log4j version 1.2: A widely used open–source logging framework
  • JDK 1.4 logging: A logging API provided by Java
  • JCL: An open-source Commons logging framework that provides an interface with thin wrapper implementations for other logging tools
  • Logback: A serializable logger that logs after its deserialization, depending on the chosen binding

To set up logging, you need the slf4j-api.jar file in your classpath, together with the JAR file for your preferred binding: slf4j-log4j12.jar in the case of log4j. You can also enable a property called showsql to see the exact query being executed. You can configure a logging layer such as Apache log4j to enable Hibernate class- or package-level logging. And you can use the Statistics interface provided by Hibernate to obtain detailed information.

How It Works

You have to configure the Hibernate show_sql property to enable logging.

Inspecting the SQL Statements Issued by Hibernate

Hibernate generates SQL statements that enable you to access the database behind the scene. You can set the show_sql property to true in the hibernate.cfg.xml XML configuration file to print the SQL statements to stdout:

<property name="show_sql">true</property>

Enabling Live Statistics

You can enable live statistics by setting the hibernate.generate_statistics property in the configuration file:

<property name="hibernate.generate_statistics">true</property>

You can also access statistics programmatically by using the Statistics interfaces. Hibernate provides SessionStatistics and Statistics interfaces in the org.hibernate.stat package. The following code shows the use of some utility methods:

 SessionFactory sessionFactory = SessionManager.getSessionFactory();
session = sessionFactory.openSession();
SessionStatistics sessionStats = session.getStatistics();
Statistics stats = sessionFactory.getStatistics();
tx = session.beginTransaction();
Publisher publisher = new Publisher();
publisher.setCode("apress");
publisher.setName("Apress");
publisher.setAddress("233 Spring Street, New York, NY 10013");
session.persist(publisher);
tx.commit();
logger.info("getEntityCount- " + sessionStats.getEntityCount());
logger.info("openCount- " + stats.getSessionOpenCount());
logger.info("getEntityInsertCount- " + stats.getEntityInsertCount());
stats.logSummary();
session.close();

The output of this code sample is shown here (the complete log is given for clarity):

HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
HHH000412: Hibernate Core {4.3.5.Final}
HHH000206: hibernate.properties not found HHH000021: Bytecode provider name : javassist
HHH000043: Configuring from resource: /hibernate.cfg.xml
HHH000040: Configuration resource: /hibernate.cfg.xml
HHH000221: Reading mappings from resource: com/apress/hibernaterecipes/chapter1/model/Book.hbm.xml
HHH000221: Reading mappings from resource: com/apress/hibernaterecipes/chapter1/model/Publisher.hbm.xml
HHH000041: Configured SessionFactory: null
HHH000402: Using Hibernate built-in connection pool (not for production use!)
HHH000401: using driver [org.hsqldb.jdbcDriver] at URL [jdbc:hsqldb:file:./chapter1;write_delay=false]
HHH000046: Connection properties: {}
HHH000006: Autocommit mode: false
HHH000115: Hibernate connection pool size: 20 (min=1)
HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
HHH000399: Using default transaction strategy (direct JDBC transactions)
HHH000397: Using ASTQueryTranslatorFactory
HHH000227: Running hbm2ddl schema export
HHH000230: Schema export complete Session Metrics {    
  14000 nanoseconds spent acquiring 1 JDBC connections;     0 nanoseconds spent releasing 0 JDBC connections;     2445000 nanoseconds spent preparing 2 JDBC statements;     1636000 nanoseconds spent executing 2 JDBC statements;     0 nanoseconds spent executing 0 JDBC batches;     0 nanoseconds spent performing 0 L2C puts;     0 nanoseconds spent performing 0 L2C hits;     0 nanoseconds spent performing 0 L2C misses;     0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);     59000 nanoseconds spent executing 2 partial-flushes (flushing a total of 0 entities and 0 collections) } getEntityCount- 1 openCount- 2 getEntityInsertCount- 1 HHH000161: Logging statistics....
HHH000251: Start time: 1408349026472 HHH000242: Sessions opened: 2
HHH000241: Sessions closed: 1 HHH000266: Transactions: 2
HHH000258: Successful transactions: 2
HHH000187: Optimistic lock failures: 0
HHH000105: Flushes: 1
HHH000048: Connections obtained: 2
HHH000253: Statements prepared: 3
HHH000252: Statements closed: 0
HHH000239: Second level cache puts: 0
HHH000237: Second level cache hits: 0
HHH000238: Second level cache misses: 0
HHH000079: Entities loaded: 0
HHH000080: Entities updated: 0
HHH000078: Entities inserted: 1
HHH000076: Entities deleted: 0
HHH000077: Entities fetched (minimize this): 0
HHH000033: Collections loaded: 0
HHH000036: Collections updated: 0
HHH000035: Collections removed: 0
HHH000034: Collections recreated: 0
HHH000032: Collections fetched (minimize this): 0
HHH000438: NaturalId cache puts: 0
HHH000439: NaturalId cache hits: 0 HHH000440: NaturalId cache misses: 0
HHH000441: Max NaturalId query time: 0ms
HHH000442: NaturalId queries executed to database: 0
HHH000210: Queries executed to database: 0
HHH000215: Query cache puts: 0 HHH000433: update timestamps cache puts: 0
HHH000434: update timestamps cache hits: 0
HHH000435: update timestamps cache misses: 0
HHH000213: Query cache hits: 0
HHH000214: Query cache misses: 0
HHH000173: Max query time: 0ms Session Metrics {     5000 nanoseconds spent acquiring 1 JDBC connections;     0 nanoseconds spent releasing 0 JDBC connections;     262000 nanoseconds spent preparing 1 JDBC statements;     828000 nanoseconds spent executing 1 JDBC statements;     0 nanoseconds spent executing 0 JDBC batches;     0 nanoseconds spent performing 0 L2C puts;     0 nanoseconds spent performing 0 L2C hits;     0 nanoseconds spent performing 0 L2C misses;     8131000 nanoseconds spent executing 1 flushes (flushing a total of 1 entities and 0 collections);     0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections) }

Hibernate中启用日志的更多相关文章

  1. Hibernate使用Log4j日志记录(使用properties文件)

    我们知道,Log4j和Logback框架可用于支持日志记录hibernate,使用log4j有两种执行日志记录的方法: 通过log4j.xml文件(或) 通过log4j.properties文件 在这 ...

  2. Hibernate使用Log4j日志记录(使用xml文件)

    日志记录使程序员能够将日志详细信息永久写入文件. Log4j和Logback框架可以在hibernate框架中使用来支持日志记录. 使用log4j执行日志记录有两种方法: 通过log4j.xml文件( ...

  3. hibernate学习(9)——日志,一对一,二级缓存

    1.Hibernate中的日志 1  slf4j 核心jar  : slf4j-api-1.6.1.jar .slf4j是日志框架,将其他优秀的日志第三方进行整合. 整合导入jar包 log4j 核心 ...

  4. hibernate中的缓存机制

    一.为什么要用Hibernate缓存? Hibernate是一个持久层框架,经常访问物理数据库. 为了降低应用程序对物理数据源访问的频次,从而提高应用程序的运行性能. 缓存内的数据是对物理数据源中的数 ...

  5. 【Azure Application Insights】在Azure Function中启用Application Insights后,如何配置不输出某些日志到AI 的Trace中

    问题描述 基于.NET Core的Function App如果配置了Application Insights之后,每有一个函数被执行,则在Application Insights中的Logs中的tra ...

  6. 【Hibernate】解析hibernate中的缓存

    Hibernate中的缓存一共有三种,一级缓存.二级缓存.查询缓存.缓存除了使用Hibernate自带的缓存,还可以使用redis进行缓存,或是MongoDB进行缓存. 所使用的Demo: User. ...

  7. Java三大框架之——Hibernate中的三种数据持久状态和缓存机制

    Hibernate中的三种状态   瞬时状态:刚创建的对象还没有被Session持久化.缓存中不存在这个对象的数据并且数据库中没有这个对象对应的数据为瞬时状态这个时候是没有OID. 持久状态:对象经过 ...

  8. mysql的innodb中事务日志ib_logfile

    mysql的innodb中事务日志ib_logfile事务日志或称redo日志,在mysql中默认以ib_logfile0,ib_logfile1名称存在,可以手工修改参数,调节开启几组日志来服务于当 ...

  9. ns3 Tutorial 中的日志模块(翻译)

      转载地址:http://blog.sina.com.cn/s/blog_8ecca79b0101d7fe.html     1  日志模块的使用   在运行 first.cc 脚本时,我们已经简单 ...

随机推荐

  1. Silverlight取得Session

    首先Session是运行在服务器上的,而Silverlight运行在客户端.因此在Silverlight中使用SESSION的说法并不准确, 只因大家经常这样搜索才起这个名字. 有两种方法实现Silv ...

  2. jquery中each()函数

    今天在使用each函数时,发现写的js代码明明木有问题,为什么点击没有执行呢.js始终处于入门阶段,只好瞎鼓捣. 弄了半天,总算可以了.代码如下: <script type="text ...

  3. 【MySql】5.6.14版本的安装和测试

    当前状态:apache2.4.6和php5.5.6已经安装成功: mysql的安装和测试: 一.安装mysql5.6.14,参考http://wenku.baidu.com/link?url=_0jk ...

  4. 通过Messenger与后台连接(单向操作,activity向service发送数据)

    xml: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:t ...

  5. 【Delphi】注册快捷键

    ShortCutToText , TextToShortCut 需 uses Menus; type TForm1 = class(TForm) HotKey1: THotKey; Button1: ...

  6. JAVA里的字符串,String 类简单介绍

    http://www.360doc.com/content/14/1107/23/17130779_423471141.shtml

  7. Keil的使用方法 - 常用功能(一)

    Ⅰ.概述 学习一门软件的开发,开发工具的掌握可以说尤为重要.由于Keil集成开发工具支持多种MCU平台的开发,是市面上比较常见的,也是功能比较强大一款IDE.所以,对于大多数人说,选择Keil几乎是单 ...

  8. Bash美化

    首先声明下,这些美化方式都不是我自己想的,而是多个牛人的方法. 第一:简单点 这个方法来自于:http://www.vimer.cn/?p=1554 没有美化前是这样,鼠标光标在很右边: 在.bash ...

  9. 从数组->ArrayList->List 为了方便与安全在不断变化着

    在C#中,当我们想要存储一组对象的时候,就会想到用数组,ArrayList,List这三个对象了. 数组 优点优点之一:数组在内存中是连续存储的,所以它的索引速度是非常的快,而且赋值与修改元素也很简单 ...

  10. Android--获取使用的总流量和每个App的上传、下载的流量

    获得每个App的上传.下载的流量. 思路就是获取到我们手机上的所有app,再获得app里面使用的权限,如果app有网络权限,就显示出来. 代码很简单,代码里面也有比较详细的注释,下面直接上代码 布局文 ...