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

org.hibernate.AnnotationException: Unknown Id.generator

Problem Runing the following Hibernate’s annotation sequence generator with PostgreSQL database. @Id @Column(name="user_id", nullable=false) @GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="account_user_id_seq") private Integer userId; Hits the following Unknown Id.generator exception. Caused by: org.hibernate.AnnotationException: Unknown Id.generator: account_user_id_seq at org.hibernate.cfg.BinderHelper.makeIdGenerator(BinderHelper.java:413) at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1795) at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1229) at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:733) The sequence “account_user_id_seq” is created in PostgreSQL database, what caused the above exception? Solution …

Read more

How to display hibernate sql parameter values – P6Spy

Question There are many developers asking about Hibernate SQL parameter value question. How to display the Hibernate SQL parameter values that passed to database? Hibernate just display all parameter values as question mark (?). With show_sql property, Hibernate will shows all generated SQL statements, but not the SQL parameter values. For example Hibernate: insert into …

Read more

Remember that ordinal parameters are 1-based! – HibernateTemplate

Problem HibernateTemplate code … getHibernateTemplate().find("from Domain d where d.domainName = :domainName", domainName); When i execute the above code, i hit the following error message java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based! … at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:397) at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:369) Solution I go inside and study HibernateTemplate.java file and find below code public List find(final String queryString, final Object[] …

Read more

Why i choose Hibernate for my project?

Currently my company is using IBATIS and pure SQLs as database persistence mechanism. I like SQL query very much, especially in tuning, but i do not like to write all SQL statement in Java application, it’s easy to hit typo error and what a stupid and tedious job? Finally my company has a new project …

Read more