Hibernate interceptor example – audit log

Hibernate has a powerful feature called ‘interceptor‘ to intercept or hook different kind of Hibernate events, like database CRUD operation. In this article, i will demonstrate how to implement an application audit log feature by using Hibernate interceptor, it will log all the Hibernate save, update or delete operations into a database table named ‘auditlog‘. …

Read more

Hibernate mutable example (class and collection)

In hibernate, ‘mutable‘ is default to ‘true’ in class and its related collection, it mean the class or collection are allow to add, update and delete. On the other hand, if the mutable is changed to false, it has different meaning in class and its related collection. Let’s take some examples to understand more about …

Read more

How to embed Oracle hints in Hibernate query

With Oracle hints, you can alter the Oracle execution plans to affect the way how Oracle retrieve the data from database. Go here for more detail about Oracle optimizer hints. In Hibernate, is this possible to embed the Oracle hint into the Hibernate query? Hibernate setComment()? Can you embed the Oracle hint into HQL with …

Read more

How to call stored procedure in Hibernate

In this tutorial, you will learn how to call a store procedure in Hibernate. MySQL store procedure Here’s a MySQL store procedure, which accept a stock code parameter and return the related stock data. DELIMITER $$ CREATE PROCEDURE `GetStocks`(int_stockcode varchar(20)) BEGIN SELECT * FROM stock where stock_code = int_stockcode; END $$ DELIMITER ; In MySQL, …

Read more

Hibernate parameter binding examples

Without parameter binding, you have to concatenate the parameter String like this (bad code) : String hql = "from Stock s where s.stockCode = ‘" + stockCode + "’"; List result = session.createQuery(hql).list(); Pass an unchecked value from user input to the database will raise security concern, because it can easy get hack by SQL …

Read more

Hibernate native SQL queries examples

In Hibernate, HQL or criteria queries should be able to let you to execute almost any SQL query you want. However, many developers are complaint about the Hibernate’s generated SQL statement is slow and more prefer to generated their own SQL (native SQL) statement. Native SQL queries example Hibernate provide a createSQLQuery method to let …

Read more

Hibernate named query examples

Often times, developer like to put HQL string literals scatter all over the Java code, this method is hard to maintaine and look ugly. Fortunately, Hibernate come out a technique called “names queries” , it lets developer to put all HQL into the XML mapping file or via annotation. How to declare named query The …

Read more

Hibernate Query examples (HQL)

Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name. HQL is extremely simple to learn and use, and the code is always self-explanatory. 1. HQL …

Read more

Hibernate Transaction handle example

In Hibernate, the transaction management is quite standard, just remember any exceptions thrown by Hibernate are FATAL, you have to roll back the transaction and close the current session immediately. Here’s a Hibernate transaction template : Session session = null; Transaction tx = null; try{ session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); tx.setTimeout(5); //doSomething(session); tx.commit(); }catch(RuntimeException …

Read more

Hibernate – Many-to-Many example (XML Mapping)

Many-to-many relationships occur when each record in an entity may have many linked records in another entity and vice-versa. In this tutorial, we show you how to work with many-to-many table relationship in Hibernate, via XML mapping file (hbm). Note For many to many with extra columns in join table, please refer to this tutorial. …

Read more

Different between cascade and inverse

Many Hibernate developers are confuse about the cascade option and inverse keyword. In some ways..they really look quite similar at the beginning, both are related with relationship. Cascade vs inverse However, there is no relationship between cascade and inverse, both are totally different notions. 1. inverse This is used to decide which side is the …

Read more

Different between session.get() and session.load()

Often times, you will notice Hibernate developers mix use of session.get() and session load(), do you wonder what’s the different and when you should use either of it? Different between session.get() and session.load() Actually, both functions are use to retrieve an object with different mechanism, of course. 1. session.load() It will always return a “proxy” …

Read more

Hibernate – One-to-One example (XML Mapping)

A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. In this tutorial, we show you how to work with one-to-one table relationship in Hibernate, via XML mapping file (hbm). Tools and technologies used in this tutorials : Hibernate 3.6.3.Final MySQL 5.1.15 Maven 3.0.3 Eclipse 3.6 Project Structure See …

Read more

Hibernate – Cascade example (save, update, delete and delete-orphan)

Cascade is a convenient feature to save the lines of code needed to manage the state of the other side manually. The “Cascade” keyword is often appear on the collection mapping to manage the state of the collection automatically. In this tutorials, this one-to-many example will be used to demonstrate the cascade effect. Cascade save …

Read more

Hibernate – One-to-Many example (XML Mapping)

A one-to-many relationship occurs when one entity is related to many occurrences in another entity. In this tutorial, we show you how to works with one-to-many table relationship in Hibernate, via XML mapping file (hbm). Tools and technologies used in this tutorials : Hibernate 3.6.3.Final MySQL 5.1.15 Maven 3.0.3 Eclipse 3.6 Project Structure Project structure …

Read more

inverse = “true” example and explanation

Always put inverse=”true” in your collection variable ? There are many Hibernate articles try to explain the “inverse” with many Hibernate “official” jargon, which is very hard to understand (at least to me). In few articles, they even suggested that just forget about what is “inverse”, and always put inverse=”true” in the collection variable. This …

Read more

Hibernate – dynamic-update attribute example

What is dynamic-update The dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE statement. Dynamic-update example 1. dynamic-update=false The default value of dynamic-update is false, which means include unmodified properties in the Hibernate’s SQL update statement. For example, get an object and try modify its value and update it. Query q …

Read more

Hibernate – dynamic-insert attribute example

What is dynamic-insert The dynamic-insert attribute tells Hibernate whether to include null properties in the SQL INSERT statement. Let explore some examples to understand more clear about it. Dynamic-insert example 1. dynamic-insert=false The default value of dynamic-insert is false, which means include null properties in the Hibernate’s SQL INSERT statement. For example, try set some …

Read more

How to display hibernate sql parameter values – Log4j

Problem Hibernate has basic logging feature to display the SQL generated statement with show_sql configuration property. Hibernate: INSERT INTO mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME) VALUES (?, ?, ?, ?, ?, ?) However , it just isn’t enough for debugging, the Hibernate SQL parameter values are missing. Solution – Log4j Log4J is required to …

Read more

Display Hibernate SQL to console – show_sql , format_sql and use_sql_comments

Hibernate has build-in a function to enable the logging of all the generated SQL statements to the console. You can enable it by add a “show_sql” property in the Hibernate configuration file “hibernate.cfg.xml“. This function is good for basic troubleshooting, and to see what’s Hibernate is doing behind. 1. show_sql Enable the logging of all …

Read more

Maven 2 + Hibernate 3.2 + MySQL Example (Annotation)

Note This article is outdated, and some information is no longer valid in latest Hibernate development. You should refer to this latest – Maven 3 + Hibernate 3.6.3 + Oracle 11g Example (Annotation) tutorial. This tutorial will modify the previous Maven 2 + Hibernate 3.2 + MySQL Example (XML mapping), and replace the Hibernate XML …

Read more

How to configure logging in Hibernate – SLF4j + Log4j

Try logback Try logback logging framework, read this article for the “reasons to prefer logback over log4j. To integrate logback with Hibernate, refer this – How to configure logging in Hibernate – Logback Hibernate uses Simple Logging Facade for Java (SLF4J) to redirect the logging output to your perfer logging frameworkis (log4j, JCL, JDK logging, …

Read more

Hibernate Error – Exception in thread “main” java.lang.NoClassDefFoundError: antlr/ANTLRException

This is caused by missing of the antlr library. It’s usually happened when you did invoke Hibernate’s query statement. Exception in thread "main" java.lang.NoClassDefFoundError: antlr/ANTLRException at org.hibernate.hql.ast.ASTQueryTranslatorFactory.createQueryTranslator(ASTQueryTranslatorFactory.java:35) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:74) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623) at com.mkyong.common.App.main(App.java:23) Caused by: java.lang.ClassNotFoundException: antlr.ANTLRException at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager

This is caused by missing of the Hibernate commons annotations library. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:11) Caused by: java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13) … 2 more Caused by: java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.ReflectionManager at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) …

Read more

Hibernate Error – An AnnotationConfiguration instance is required to use

The Hibernate annotation is required “AnnotationConfiguration” instead of normal “Configuration()” to build the session factory. INFO: Configuration resource: /hibernate.cfg.xml Initial SessionFactory creation failed.org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.mkyong.common.Stock"/> Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:11) Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.mkyong.common.Stock"/> …

Read more

Hibernate SQL Dialects Collection

Hibernate SQL Dialect is telling your Hibernate application which SQL language should be use to talk with your database. 1. DB2 org.hibernate.dialect.DB2Dialect 2. DB2 AS/400 org.hibernate.dialect.DB2400Dialect 3. DB2 OS390 org.hibernate.dialect.DB2390Dialect 4. PostgreSQL org.hibernate.dialect.PostgreSQLDialect 5. MySQL org.hibernate.dialect.MySQLDialect 6. MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect 7. MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect 8. Oracle 8 org.hibernate.dialect.OracleDialect 9. Oracle 9i/10g org.hibernate.dialect.Oracle9Dialect 10. …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources

Hibernate’s “C3P0” connection pool error, this is caused by the missing dependency library – C3P0. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:11) Caused by: java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources at org.hibernate.connection.C3P0ConnectionProvider.configure(C3P0ConnectionProvider.java:154) at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124) at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56) at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:410) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292) at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13) … 2 more Caused …

Read more

How to add Hibernate XML mapping file (hbm.xml) programmatically

Hibernate XML mapping file contains the mapping relationship between Java class and database table. This is always named as “xx.hbm.xml” and declared in the Hibernate configuration file “hibernate.cfg.xml”. For example, the mapping file (hbm.xml) is declared in the “mapping” tag <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.bytecode.use_reflection_optimizer">false</property> …

Read more

How to configure the C3P0 connection pool in Hibernate

Connection Pool Connection pool is good for performance, as it prevents Java application create a connection each time when interact with database and minimizes the cost of opening and closing connections. See wiki connection pool explanation Hibernate comes with internal connection pool, but not suitable for production use. In this tutorial, we show you how …

Read more

How to load hibernate.cfg.xml from different directory

Hibernate XML configuration file “hibernate.cfg.xml” is always put at the root of your project classpath, outside of any package. If you place this configuration file into a different directory, you may encounter the following error : Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:25) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:11) Caused …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter

A common Hibernate’s error, this is caused by the missing dependency library – cglib. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:17) Caused by: java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter at org.hibernate.bytecode.cglib.BytecodeProviderImpl.getProxyFactoryFactory(BytecodeProviderImpl.java:33) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactoryInternal(PojoEntityTuplizer.java:182) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:160) at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:135) at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:55) at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:56) at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:295) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:434) at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:109) at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:55) at …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap

A common Hibernate’s error, this is caused by the missing dependency library – Apache Common Collection. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:17) Caused by: java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap at org.hibernate.mapping.Table.<init>(Table.java:33) at org.hibernate.cfg.Mappings.addTable(Mappings.java:165) at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:290) at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:273) at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:144) at org.hibernate.cfg.Configuration.add(Configuration.java:669) at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:504) at org.hibernate.cfg.Configuration.addResource(Configuration.java:566) at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1587) at …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

A common Hibernate’s error, this is caused by the missing dependency library – Common Logging. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:17) Caused by: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:120) at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13) … 2 more Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) …

Read more

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/dom4j/DocumentException

A common Hibernate’s error, this is caused by the missing dependency library – dom4j. Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/dom4j/DocumentException Exception in thread "main" java.lang.ExceptionInInitializerError at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8) at com.mkyong.common.App.main(App.java:17) Caused by: java.lang.NoClassDefFoundError: org/dom4j/DocumentException at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13) … 2 more Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at …

Read more

How to generate Hibernate mapping files & annotation with Hibernate Tools

In this article, we show you how to use Hibernate / JBoss Tools to generate Hibernate mapping files (hbm) and annotation code from database automatically. Tools in this article Eclipse v3.6 (Helios) JBoss / Hibernate Tools v3.2 Oracle 11g JDK 1.6 Note Before proceed, please Install Hibernate / JBoss Tools in Eclipse IDE. 1. Hibernate …

Read more

How to install Hibernate / JBoss Tools in Eclipse IDE

Hibernate Tools is a handy tool for Java’s developers to generate tedious hibernate related stuffs like mapping files and annotation code. The common use case is the “reverse engineering” feature to generate Hibernate model class, hbm mapping file or annotation code from database tables. Note Hibernate Tools is bundled as the core component of JBoss …

Read more