Enable Logging in Hibernate and enable logging in Hibernate
Enable Logging in Hibernate
Author: chszs, reprinted with note. Blog homepage: http://blog.csdn.net/chszs
In the project, if you want to troubleshoot and identify bugs, you cannot leave the log information. How can I enable log output in the Hibernate project? This article describes how to enable logs in Hibernate and the log level of Hibernate.
I. Project Development Environment
Take an example project as an example. Our project uses:
Ii. Dependency
The example project uses the following open-source libraries:
1. hibernate-core
Core library of ORM persistence
2. mysql-connector-java
MySQL JDBC driver package
3. slf4j-api
Simple log Facade for Hibernate
4. slf4j-log4j12
The log output library used by Hibernate
5. ipvsist
Java bytecode library used by Hibernate
Hibernate depends on the abstract log framework SLF4J. After using SLF4J, you can select multiple log output frameworks. If the project is not bound to any log output framework, there is no output. Therefore, this example project is bound with Log4j as the log output framework.
3. Configure Log4j
In the project's class path, create the log4j. properties file with the following content:
# Root logger optionlog4j.rootLogger=INFO, consolelog4j.logger.com.ch.demo=INFO, console# Direct log messages to consolelog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.Target=System.outlog4j.appender.console.layout=org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern=%d{HH:mm}| %p | %F %L | %m%n# direct messages to file hibernate.loglog4j.logger.org.hibernate=DEBUG, hibernatelog4j.appender.hibernate=org.apache.log4j.RollingFileAppenderlog4j.appender.hibernate.File=hibernate.loglog4j.appender.hibernate.layout=org.apache.log4j.PatternLayoutlog4j.appender.hibernate.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
In the above log4j. properties configuration file, we specify the specific information output category of all Hibernate as hibernate. log. It is used in the org. hibernate package. If you only want to output some information about the Hibernate category, you need to configure the specified category.
The main types of Hibernate are as follows:
1) org. hibernate. SQL
Log output all SQL DML statements executed by Hibernate
2) org. hibernate. type
Log output all JDBC Parameters
3) org. hibernate. transaction
Logs output all activity-related transactions
4) org. hibernate. jdbc
Log output all JDBC Resource Collection
5) org. hibernate. tool. hbm2ddl
Log output all SQL DDL statements executed by Hibernate
6) org. hibernate
Logs output all Hibernate Information
If the log output category is org. hibernate. SQL, the SQL statement is output. However, there is also a simpler way to view SQL statements. You only need to set the show_ SQL parameter to true.
Iv. Hibernate log Example 1. Create an object 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. Create An ORM ing file: orders. hbm. xml
<!DOCTYPE hibernate-mappingPUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
3. Sample Code for database operation: 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. log output 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 -> org.hibernate.type.BooleanType@55f616cf19:14| DEBUG | BasicTypeRegistry.java 130 | Adding type registration boolean -> org.hibernate.type.BooleanType@55f616cf19:14| DEBUG | BasicTypeRegistry.java 130 | Adding type registration java.lang.Boolean -> org.hibernate.type.BooleanType@55f616cf...19:14| DEBUG | ErrorCounter.java 95 | throwQueryException() : no errors19: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 (?, ?, ?, ?)