在Hibernate中开启日志
作者:chszs,转载需注明。博客主页:http://blog.csdn.net/chszs
在项目中,如果要排查故障,找出Bug,离不开日志信息。那么在Hibernate项目中如何开启日志输出呢?本文讲述如何在Hibernate中开启日志,以及Hibernate的日志级别。
一、项目开发环境
具体以一个示例项目为例,我们的项目使用了:
- Maven 3.2.3
- Hibernate 5.0.0.CR1 RELEASE
- Eclipse IDE,版本为Luna 4.4.1
二、依赖关系
示例项目使用了以下的开源库,包括:
1. hibernate-core
ORM持久化的核心库
2. mysql-connector-java
MySQL的JDBC驱动包
3. slf4j-api
供Hibernate使用的简单日志Facade
4. slf4j-log4j12
Hibernate使用的日志输出库
5. javassist
Hibernate使用的Java字节码操作库
Hibernate依赖于抽象日志框架SLF4J,使用SLF4J后,可以选择多种日志输出框架。如果项目未绑定任何日志输出框架,那么它是没有任何输出的。故本示例项目绑定了Log4j作为日志输出框架。
三、配置Log4j
在项目的类路径下,创建log4j.properties文件,内容如下:
# Root logger option
log4j.rootLogger=INFO, console
log4j.logger.com.ch.demo=INFO, console
# Direct log messages to console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{HH:mm}| %p | %F %L | %m%n
# direct messages to file hibernate.log
log4j.logger.org.hibernate=DEBUG, hibernate
log4j.appender.hibernate=org.apache.log4j.RollingFileAppender
log4j.appender.hibernate.File=hibernate.log
log4j.appender.hibernate.layout=org.apache.log4j.PatternLayout
log4j.appender.hibernate.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
上面的log4j.properties配置文件中,我们指定所有的Hibernate的具体信息输出类别为hibernate.log。它用于org.hibernate包。如果只想输出部分Hibernate类别的信息,那么需要对指定类别进行配置。
Hibernate主要的类别如下:
1)org.hibernate.SQL
日志输出所有Hibernate执行的SQL DML语句
2)org.hibernate.type
日志输出所有的JDBC参数
3)org.hibernate.transaction
日志输出所有活动相关的事务
4)org.hibernate.jdbc
日志输出所有的JDBC资源采集
5)org.hibernate.tool.hbm2ddl
日志输出所有Hibernate执行的SQL DDL语句
6)org.hibernate
日志输出所有的Hibernate信息
如果指定日志输出类别为org.hibernate.SQL,那么将会输出SQL语句。但是,还有一种更简单的查看SQL语句的方法,只需简单地设置show_sql参数为true。
四、Hibernate日志示例
1、创建实体Bean:Order
package com.ch.demo.hibernate;
import java.util.Date;
public class Order {
private Long orderId;
private String orderNbr;
private Date orderDate;
private String orderDesc;
private Long orderQty;
public Order() {
}
public Order(String orderNbr) {
this.orderNbr = orderNbr;
}
public Long getOrderId() {
return orderId;
}
private void setOrderId(Long orderId) {
this.orderId = orderId;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getOrderDesc() {
return orderDesc;
}
public void setOrderDesc(String orderDesc) {
this.orderDesc = orderDesc;
}
public Long getOrderQty() {
return orderQty;
}
public void setOrderQty(Long orderQty) {
this.orderQty = orderQty;
}
public String toString() {
return "Order: nbr[" + orderNbr + "] date [" + orderDate + "] desc["
+ orderDesc + "] qty[" + orderQty + "]";
}
}
2、创建ORM映射文件:orders.hbm.xml
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ch.demo.hibernate">
<class name="com.ch.demo.hibernate.Order" table="orders">
<id name="orderId" column="order_id">
<generator class="native" />
</id>
<property name="orderNbr" column="order_nbr" type="string" length="30" access="field"/>
<property name="orderDesc" column="order_desc" type="string"
length="60" />
<property name="orderDate" type="timestamp" column="order_date"/>
<property name="orderQty" column="qty" type="long" />
</class>
</hibernate-mapping>
3、操作数据库的示例代码:HibernateLoggingExample.java
package com.ch.demo.hibernate;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.hibernate.MappingException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateLoggingExample {
public static void main(String[] args) throws MappingException, IOException {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.getTransaction();
tx.begin();
Query query = session.createQuery("from Order where orderNbr=‘ORD01‘");
List list = query.list();
System.out.println("Orders found: " + list.size());
for(Order order: list) {
session.delete(order);
System.out.println("Deleted " + order);
}
tx.commit();
session = sessionFactory.getCurrentSession();
tx = session.getTransaction();
tx.begin();
Order order = new Order("ORD01");
order.setOrderDesc("Laptop");
order.setOrderQty(2L);
order.setOrderDate(new Date());
session.save(order);
tx.commit();
session = sessionFactory.getCurrentSession();
tx = session.getTransaction();
tx.begin();
query = session.createQuery("from Order where orderNbr=‘ORD01‘");
System.out.println("List all orders: " + query.list());
tx.commit();
sessionFactory.close();
}
}
4、日志输出
19:14| DEBUG | IntegratorServiceImpl.java 46 | Adding Integrator [org.hibernate.cfg.beanvalidation.BeanValidationIntegrator].
19:14| DEBUG | IntegratorServiceImpl.java 46 | Adding Integrator [org.hibernate.secure.spi.JaccIntegrator].
19:14| DEBUG | IntegratorServiceImpl.java 46 | Adding Integrator [org.hibernate.cache.internal.CollectionCacheInvalidator].
...
19:14| DEBUG | LocalXmlResourceResolver.java 74 | Recognized legacy hibernate-mapping identifier; attempting to resolve on classpath under org/hibernate/
19:14| DEBUG | MappingBinder.java 53 | Performing JAXB binding of hbm.xml document : Origin(name=orders.hbm.xml,type=RESOURCE)
19:14| DEBUG | BasicTypeRegistry.java 130 | Adding type registration boolean -> [email protected]
19:14| DEBUG | BasicTypeRegistry.java 130 | Adding type registration boolean -> [email protected]
19:14| DEBUG | BasicTypeRegistry.java 130 | Adding type registration java.lang.Boolean -> [email protected]
...
19:14| DEBUG | ErrorCounter.java 95 | throwQueryException() : no errors
19:14| DEBUG | QueryTranslatorImpl.java 246 | HQL: from com.ch.demo.hibernate.Order where orderNbr=‘ORD01‘
19:14| DEBUG | QueryTranslatorImpl.java 247 | SQL: select order0_.order_id as order_id1_0_, order0_.order_nbr as order_nb2_0_, order0_.order_desc as order_de3_0_, order0_.order_date as order_da4_0_, order0_.qty as qty5_0_ from orders order0_ where order0_.order_nbr=‘ORD01‘
19:14| DEBUG | ErrorCounter.java 95 | throwQueryException() : no errors
...
19:14| DEBUG | SqlStatementLogger.java 92 | delete from orders where order_id=?
Hibernate: delete from orders where order_id=?
...
19:14| DEBUG | SqlStatementLogger.java 92 | insert into orders (order_nbr, order_desc, order_date, qty) values (?, ?, ?, ?)
Hibernate: insert into orders (order_nbr, order_desc, order_date, qty) values (?, ?, ?, ?)