JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

How to enable logging (log4j) in Hibernate?


Logging is an important step in our application development. This enable us to debug our code and identify the code execution. The log4j librery is a most popular logging framework. In this page, we will see how to enable logging using Log4j framework in Hibernate.

As a first step, add slf4j-log4j12 into your pom.xml file.

Here is a sample pom.xml for your reference:

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.java2novice</groupId>
	<artifactId>hibernate-examples</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>hibernate-examples</name>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>
		<!-- Hibernate core dependency -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.0.0.Final</version>
		</dependency>
		<!-- MySQL database driver -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.25</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.11</version>
		</dependency>

	</dependencies>
</project>

Log4j Property File

First make sure your application has log4j.properties file added to your application classpath. The default category to display all hibernate log messages to your log file is "org.hibernate". But remember that this adds lot of log messages to your log file.

You can choose specific log messages in hibernate category. They are:

  1. org.hibernate.SQL: Log all SQL DML statements as they are executed.
  2. org.hibernate.type: Log all JDBC parameters.
  3. org.hibernate.transaction: Log transaction related activity.
  4. org.hibernate.jdbc: Log all JDBC resource acquisition.
  5. org.hibernate.tool.hbm2ddl: Log all SQL DDL statements as they are executed.
  6. org.hibernate: Log all hibernate messages.

log4j.properties
# Root logger option
log4j.rootLogger=INFO, console
 
log4j.logger.com.javarticles=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
 
# hibernate log configurations
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

Output:
12:23| DEBUG | AbstractEntityPersister.java 3418 | Static SQL for entity: com.java2novice.model.Employee
12:23| DEBUG | AbstractEntityPersister.java 3423 |  Version select: select EMP_ID from EMPLOYEES where EMP_ID =?
12:23| DEBUG | AbstractEntityPersister.java 3426 |  Snapshot select: select employee_.EMP_ID, employee_.department as departme2_1_, employee_.JOINED_ON as JOINED_O3_1_, employee_.name as name4_1_, employee_.salary as salary5_1_ from EMPLOYEES employee_ where employee_.EMP_ID=?
12:23| DEBUG | DelegatingBasicLogger.java 394 |  Insert 0: insert into EMPLOYEES (department, JOINED_ON, name, salary, EMP_ID) values (?, ?, ?, ?, ?)
12:23| DEBUG | DelegatingBasicLogger.java 394 |  Update 0: update EMPLOYEES set department=?, JOINED_ON=?, name=?, salary=? where EMP_ID=?
12:23| DEBUG | DelegatingBasicLogger.java 394 |  Delete 0: delete from EMPLOYEES where EMP_ID=?
12:23| DEBUG | AbstractEntityPersister.java 3434 |  Identity insert: insert into EMPLOYEES (department, JOINED_ON, name, salary) values (?, ?, ?, ?)
12:23| DEBUG | QuerySpacesImpl.java 174 | Adding QuerySpace : uid = <gen:0> -> org.h[email protected]b78a709]
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : department
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : empAssignmentList
12:23| DEBUG | QuerySpacesImpl.java 174 | Adding QuerySpace : uid = <gen:1> -> org.hiber[email protected]75d0911a]
12:23| DEBUG | QuerySpacesImpl.java 174 | Adding QuerySpace : uid = <gen:2> -> org.h[email protected]1c7fd41f]
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : empAssignmentList.employees
12:23| DEBUG | MetamodelGraphWalker.java 145 | Property path deemed to be circular : empAssignmentList.employees
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : empAssignmentList.name
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : empAssignmentList.owner
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : joinedOn
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : name
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : salary
12:23| DEBUG | FetchStyleLoadPlanBuildingAssociationVisitationStrategy.java 76 | Building LoadPlan...
12:23| DEBUG | LoadQueryJoinAndFetchProcessor.java 95 | processing queryspace <gen:0>
12:23| DEBUG | LoadPlanTreePrinter.java 55 | LoadPlan(entity=com.java2novice.model.Employee)
    - Returns
       - EntityReturnImpl(entity=com.java2novice.model.Employee, querySpaceUid=<gen:0>, path=com.java2novice.model.Employee)
          - CollectionAttributeFetchImpl(collection=com.java2novice.model.Employee.empAssignmentList, querySpaceUid=<gen:1>, path=com.java2novice.model.Employee.empAssignmentList)
             - (collection element) CollectionFetchableElementEntityGraph(entity=com.java2novice.model.Project, querySpaceUid=<gen:2>, path=com.java2novice.model.Employee.empAssignmentList.<elements>)
    - QuerySpaces
       - EntityQuerySpaceImpl(uid=<gen:0>, entity=com.java2novice.model.Employee)
          - SQL table alias mapping - employee0_
          - alias suffix - 0_
          - suffixed key columns - {EMP_ID1_1_0_}
          - JOIN (JoinDefinedByMetadata(empAssignmentList)) : <gen:0> -> <gen:1>
             - CollectionQuerySpaceImpl(uid=<gen:1>, collection=com.java2novice.model.Employee.empAssignmentList)
                - SQL table alias mapping - empassignm1_
                - alias suffix - 1_
                - suffixed key columns - {EMP_ID1_0_1_}
                - entity-element alias suffix - 2_
                - 2_entity-element suffixed key columns - PR_ID1_2_2_
                - JOIN (JoinDefinedByMetadata(elements)) : <gen:1> -> <gen:2>
                   - EntityQuerySpaceImpl(uid=<gen:2>, entity=com.java2novice.model.Project)
                      - SQL table alias mapping - project2_
                      - alias suffix - 2_
                      - suffixed key columns - {PR_ID1_2_2_}

12:23| DEBUG | EntityLoader.java 128 | Static select for entity com.java2novice.model.Employee [NONE]: select employee0_.EMP_ID as EMP_ID1_1_0_, employee0_.department as departme2_1_0_, employee0_.JOINED_ON as JOINED_O3_1_0_, employee0_.name as name4_1_0_, employee0_.salary as salary5_1_0_, empassignm1_.EMP_ID as EMP_ID1_0_1_, project2_.PR_ID as PR_ID2_0_1_, project2_.PR_ID as PR_ID1_2_2_, project2_.name as name2_2_2_, project2_.owner as owner3_2_2_ from EMPLOYEES employee0_ left outer join EMP_ASSIGNMENTS empassignm1_ on employee0_.EMP_ID=empassignm1_.EMP_ID left outer join PROJECTS project2_ on empassignm1_.PR_ID=project2_.PR_ID where employee0_.EMP_ID=?
12:23| DEBUG | QuerySpacesImpl.java 174 | Adding QuerySpace : uid = <gen:0> -> org.h[email protected]f79a760]
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : department
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : empAssignmentList
12:23| DEBUG | QuerySpacesImpl.java 174 | Adding QuerySpace : uid = <gen:1> -> org.hiber[email protected]12dae582]
12:23| DEBUG | QuerySpacesImpl.java 174 | Adding QuerySpace : uid = <gen:2> -> org.h[email protected]239b0f9d]
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : empAssignmentList.employees
12:23| DEBUG | MetamodelGraphWalker.java 145 | Property path deemed to be circular : empAssignmentList.employees
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : empAssignmentList.name
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : empAssignmentList.owner
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : joinedOn
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : name
12:23| DEBUG | MetamodelGraphWalker.java 137 | Visiting attribute path : salary
12:23| DEBUG | FetchStyleLoadPlanBuildingAssociationVisitationStrategy.java 76 | Building LoadPlan...
12:23| DEBUG | LoadQueryJoinAndFetchProcessor.java 95 | processing queryspace <gen:0>
12:23| DEBUG | LoadPlanTreePrinter.java 55 | LoadPlan(entity=com.java2novice.model.Employee)
    - Returns
       - EntityReturnImpl(entity=com.java2novice.model.Employee, querySpaceUid=<gen:0>, path=com.java2novice.model.Employee)
          - CollectionAttributeFetchImpl(collection=com.java2novice.model.Employee.empAssignmentList, querySpaceUid=<gen:1>, path=com.java2novice.model.Employee.empAssignmentList)
             - (collection element) CollectionFetchableElementEntityGraph(entity=com.java2novice.model.Project, querySpaceUid=<gen:2>, path=com.java2novice.model.Employee.empAssignmentList.<elements>)
    - QuerySpaces
       - EntityQuerySpaceImpl(uid=<gen:0>, entity=com.java2novice.model.Employee)
          - SQL table alias mapping - employee0_
          - alias suffix - 0_
          - suffixed key columns - {EMP_ID1_1_0_}
          - JOIN (JoinDefinedByMetadata(empAssignmentList)) : <gen:0> -> <gen:1>
             - CollectionQuerySpaceImpl(uid=<gen:1>, collection=com.java2novice.model.Employee.empAssignmentList)
                - SQL table alias mapping - empassignm1_
                - alias suffix - 1_
                - suffixed key columns - {EMP_ID1_0_1_}
                - entity-element alias suffix - 2_
                - 2_entity-element suffixed key columns - PR_ID1_2_2_
                - JOIN (JoinDefinedByMetadata(elements)) : <gen:1> -> <gen:2>
                   - EntityQuerySpaceImpl(uid=<gen:2>, entity=com.java2novice.model.Project)
                      - SQL table alias mapping - project2_
                      - alias suffix - 2_
                      - suffixed key columns - {PR_ID1_2_2_}

12:23| DEBUG | EntityLoader.java 128 | Static select for entity com.java2novice.model.Employee [READ]: select employee0_.EMP_ID as EMP_ID1_1_0_, employee0_.department as departme2_1_0_, employee0_.JOINED_ON as JOINED_O3_1_0_, employee0_.name as name4_1_0_, employee0_.salary as salary5_1_0_, empassignm1_.EMP_ID as EMP_ID1_0_1_, project2_.PR_ID as PR_ID2_0_1_, project2_.PR_ID as PR_ID1_2_2_, project2_.name as name2_2_2_, project2_.owner as owner3_2_2_ from EMPLOYEES employee0_ left outer join EMP_ASSIGNMENTS empassignm1_ on employee0_.EMP_ID=empassignm1_.EMP_ID left outer join PROJECTS project2_ on empassignm1_.PR_ID=project2_.PR_ID where employee0_.EMP_ID=?
12:23| DEBUG | QueryTranslatorImpl.java 296 | --- HQL AST ---
 \-[QUERY] Node: 'query'
    \-[SELECT_FROM] Node: 'SELECT_FROM'
       +-[FROM] Node: 'from'
       |  \-[RANGE] Node: 'RANGE'
       |     +-[DOT] Node: '.'
       |     |  +-[DOT] Node: '.'
       |     |  |  +-[DOT] Node: '.'
       |     |  |  |  +-[IDENT] Node: 'com'
       |     |  |  |  \-[IDENT] Node: 'java2novice'
       |     |  |  \-[IDENT] Node: 'model'
       |     |  \-[IDENT] Node: 'Employee'
       |     \-[ALIAS] Node: 'emp'
       \-[SELECT] Node: 'select'
          \-[IDENT] Node: 'emp'

12:23| DEBUG | ErrorCounter.java 95 | throwQueryException() : no errors
<< Previous Program 

Hibernate Examples

  1. Hibernate hello world (initial setup) example.
  2. What is hibernate.cfg.xml configuration?
  3. What are the basic hibernate persistent annotations?
  4. What is SessionFactory in Hibernate?
  5. What is Session object in Hibernate?
  6. List Hibernate Session interface methods.
  7. What is Hibernate Query object?
  8. Basic Hibernate CRUD operations example.
  9. Hibernate Bidirectional One-to-One mapping using @OneToOne annotation.
  10. Hibernate Unidirectional One-to-One mapping using @OneToOne annotation.
  11. Hibernate Eager vs Lazy Fetch Type
  12. Hibernate Unidirectional One-to-Many mapping using @OneToMany annotation.
  13. Hibernate Bidirectional One-to-Many mapping using @OneToMany annotation.
  14. Hibernate Many-to-Many mapping example using @ManyToMany annotation.
  15. How to enable logging (log4j) in Hibernate?
Knowledge Centre
What is java static import?
By using static imports, we can import the static members from a class rather than the classes from a given package. For example, Thread class has static sleep method, below example gives an idea:

import static java.lang.Thread;
public class MyStaticImportTest {
public static void main(String[] a) {
try{
sleep(100);
} catch(Exception ex){

}
}
}
Famous Quotations
Be yourself; everyone else is already taken.
-- Oscar Wilde

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2018 by Nataraja Gootooru. All Rights Reserved.