歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

在Hibernate中開啟日志

在項目中,如果要排查故障,找出Bug,離不開日志信息。那麼在Hibernate項目中如何開啟日志輸出呢?本文講述如何在Hibernate中開啟日志,以及Hibernate的日志級別。

一、項目開發環境
具體以一個示例項目為例,我們的項目使用了:
1. Maven 3.2.3
http://maven.apache.org/
2. Hibernate 5.0.0.CR1 RELEASE
http://hibernate.org/orm/
3. Eclipse IDE,版本為Luna 4.4.1
http://www.eclipse.org/

二、依賴關系
示例項目使用了以下的開源庫,包括:
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文件,內容如下:

  1. # Root logger option
  2. log4j.rootLogger=INFO, console
  3. log4j.logger.com.ch.demo=INFO, console
  4.  
  5. # Direct log messages to console
  6. log4j.appender.console=org.apache.log4j.ConsoleAppender
  7. log4j.appender.console.Target=System.out
  8. log4j.appender.console.layout=org.apache.log4j.PatternLayout
  9. log4j.appender.console.layout.ConversionPattern=%d{HH:mm}| %p | %F %L | %m%n
  10.  
  11. # direct messages to file hibernate.log
  12. log4j.logger.org.hibernate=DEBUG, hibernate
  13. log4j.appender.hibernate=org.apache.log4j.RollingFileAppender
  14. log4j.appender.hibernate.File=hibernate.log
  15. log4j.appender.hibernate.layout=org.apache.log4j.PatternLayout
  16. 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

  1. package com.ch.demo.hibernate;
  2.  
  3. import java.util.Date;
  4.  
  5. public class Order {
  6.     private Long orderId;
  7.     private String orderNbr;
  8.     private Date orderDate;
  9.     private String orderDesc;
  10.     private Long orderQty;
  11.  
  12.     public Order() {
  13.     }
  14.  
  15.     public Order(String orderNbr) {
  16.         this.orderNbr = orderNbr;
  17.     }
  18.  
  19.     public Long getOrderId() {
  20.         return orderId;
  21.     }
  22.  
  23.     private void setOrderId(Long orderId) {
  24.         this.orderId = orderId;
  25.     }
  26.  
  27.     public Date getOrderDate() {
  28.         return orderDate;
  29.     }
  30.  
  31.     public void setOrderDate(Date orderDate) {
  32.         this.orderDate = orderDate;
  33.     }
  34.  
  35.     public String getOrderDesc() {
  36.         return orderDesc;
  37.     }
  38.  
  39.     public void setOrderDesc(String orderDesc) {
  40.         this.orderDesc = orderDesc;
  41.     }
  42.  
  43.     public Long getOrderQty() {
  44.         return orderQty;
  45.     }
  46.  
  47.     public void setOrderQty(Long orderQty) {
  48.         this.orderQty = orderQty;
  49.     }
  50.  
  51.     public String toString() {
  52.         return "Order: nbr[" + orderNbr + "] date [" + orderDate + "] desc["
  53.                 + orderDesc + "] qty[" + orderQty + "]";
  54.     }
  55. }


2、創建ORM映射文件:orders.hbm.xml

  1. <!DOCTYPE hibernate-mapping
  2. PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <hibernate-mapping package="com.ch.demo.hibernate">
  5.     <class name="com.ch.demo.hibernate.Order" table="orders">
  6.         <id name="orderId" column="order_id">
  7.             <generator class="native" />
  8.         </id>
  9.         <property name="orderNbr" column="order_nbr" type="string" length="30" access="field"/>
  10.         <property name="orderDesc" column="order_desc" type="string"
  11.             length="60" />
  12.         <property name="orderDate" type="timestamp" column="order_date"/>
  13.         <property name="orderQty" column="qty" type="long" />
  14.     </class>
  15. </hibernate-mapping>


3、操作數據庫的示例代碼:HibernateLoggingExample.java

  1. package com.ch.demo.hibernate;
  2.  
  3. import java.io.IOException;
  4. import java.util.Date;
  5. import java.util.List;
  6.  
  7. import org.hibernate.MappingException;
  8. import org.hibernate.Query;
  9. import org.hibernate.Session;
  10. import org.hibernate.SessionFactory;
  11. import org.hibernate.Transaction;
  12. import org.hibernate.cfg.Configuration;
  13.  
  14. public class HibernateLoggingExample {
  15.  
  16.     public static void main(String[] args) throws MappingException, IOException {
  17.         Configuration configuration = new Configuration().configure();
  18.         SessionFactory sessionFactory = configuration.buildSessionFactory();
  19.         Session session = sessionFactory.getCurrentSession();
  20.         Transaction tx = session.getTransaction();
  21.         tx.begin();
  22.         Query query = session.createQuery("from Order where orderNbr='ORD01'");
  23.         List list = query.list();
  24.         System.out.println("Orders found: " + list.size());
  25.         for(Order order: list) {
  26.             session.delete(order);
  27.             System.out.println("Deleted " + order);
  28.         }
  29.         tx.commit();
  30.          
  31.         session = sessionFactory.getCurrentSession();
  32.         tx = session.getTransaction();
  33.         tx.begin();
  34.         Order order = new Order("ORD01");
  35.         order.setOrderDesc("Laptop");
  36.         order.setOrderQty(2L);
  37.         order.setOrderDate(new Date());
  38.         session.save(order);
  39.         tx.commit();
  40.          
  41.         session = sessionFactory.getCurrentSession();
  42.         tx = session.getTransaction();
  43.         tx.begin();
  44.         query = session.createQuery("from Order where orderNbr='ORD01'");
  45.         System.out.println("List all orders: " + query.list());
  46.         tx.commit();
  47.          
  48.         sessionFactory.close();
  49.     }
  50. }


4、日志輸出

  1. 19:14| DEBUG | IntegratorServiceImpl.java 46 | Adding Integrator [org.hibernate.cfg.beanvalidation.BeanValidationIntegrator].
  2. 19:14| DEBUG | IntegratorServiceImpl.java 46 | Adding Integrator [org.hibernate.secure.spi.JaccIntegrator].
  3. 19:14| DEBUG | IntegratorServiceImpl.java 46 | Adding Integrator [org.hibernate.cache.internal.CollectionCacheInvalidator].
  4. ...
  5. 19:14| DEBUG | LocalXmlResourceResolver.java 74 | Recognized legacy hibernate-mapping identifier; attempting to resolve on classpath under org/hibernate/
  6. 19:14| DEBUG | MappingBinder.java 53 | Performing JAXB binding of hbm.xml document : Origin(name=orders.hbm.xml,type=RESOURCE)
  7. 19:14| DEBUG | BasicTypeRegistry.java 130 | Adding type registration boolean -> org.hibernate.type.BooleanType@55f616cf
  8. 19:14| DEBUG | BasicTypeRegistry.java 130 | Adding type registration boolean -> org.hibernate.type.BooleanType@55f616cf
  9. 19:14| DEBUG | BasicTypeRegistry.java 130 | Adding type registration java.lang.Boolean -> org.hibernate.type.BooleanType@55f616cf
  10. ...
  11. 19:14| DEBUG | ErrorCounter.java 95 | throwQueryException() : no errors
  12. 19:14| DEBUG | QueryTranslatorImpl.java 246 | HQL: from com.ch.demo.hibernate.Order where orderNbr='ORD01'
  13. 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'
  14. 19:14| DEBUG | ErrorCounter.java 95 | throwQueryException() : no errors
  15. ...
  16. 19:14| DEBUG | SqlStatementLogger.java 92 | delete from orders where order_id=?
  17. Hibernate: delete from orders where order_id=?
  18. ...
  19. 19:14| DEBUG | SqlStatementLogger.java 92 | insert into orders (order_nbr, order_desc, order_date, qty) values (?, ?, ?, ?)
  20. Hibernate: insert into orders (order_nbr, order_desc, order_date, qty) values (?, ?, ?, ?)

Hibernate+JUnit測試實體類生成數據庫表  http://www.linuxidc.com/Linux/2015-07/120161.htm

Hibernate整體理解 http://www.linuxidc.com/Linux/2014-07/104405.htm

Hibernate的映射機制  http://www.linuxidc.com/Linux/2014-12/110265.htm

Hibernate 的詳細介紹:請點這裡
Hibernate 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved