Hibernate Tutorial

Hibernate, created by Gavin King, known as the best and dominated object/relational persistence (ORM) tool for Java developers (Now is support .NET). It provides many elegant and innovative ways to simplifies the relational database handling task in Java.
Hibernate is great at a lot of things, but its something that needs to be used appropriately. In this tutorials, it providing many step by step examples and explanations on using Hibernate3.
P.S Tutorials are updated to Hibernate v3.6.1.Final.
Hibernate Quick Start
Hello World example to experience the Hibernate framework.
- Maven 2 + Hibernate 3.2.3 + MySQL 5.0 Example (XML Mapping)
Hibernate 3.2.3 example in MySQL database, with classic hbm mapping. - Maven 2 + Hibernate 3.2.3 + MySQL 5.0 Example (Annotation)
Hibernate 3.2.3 example in MySQL database, with Hibernate / JPA annotation. - Maven 3 + Hibernate 3.6.3 + Oracle 11g Example (XML Mapping)
Hibernate 3.6 example in Oracle database, with classic hbm mapping. - Maven 3 + Hibernate 3.6.3 + Oracle 11g Example (Annotation)
Hibernate 3.6 example in Oracle database, with Hibernate / JPA annotation.
Hibernate Association (Table Relationship)
How to define table relationship one-to-one, one-to-many, many-to-may in Hibernate.
- One-to-One example (XML Mapping)
Hibernate one to one example with hbm mapping file. - One-to-One example (Annotation)
Hibernate one to one example with annotation code. - One-to-Many example (XML Mapping)
Hibernate one to many example with hbm mapping file. - One-to-Many example (Annotation)
Hibernate one to many example with annotation code. - Many-to-Many example (XML Mapping)
Hibernate many to many example (NO extra column in join table) with hbm mapping file. - Many-to-Many example (Annotation)
Hibernate many to many example (NO extra column in join table) with annotation code. - Many-to-Many example – join table + extra column (Annotation)
Hibernate many to many example (WITH extra column in join table) with annotation code. - Off Topic : Understand inverse keywork, example and explanation
The “inverse” is the most confusing keyword in Hibernate, but you have to understand this clearly in order to fine tune your relationship performance.
Hibernate / JBoss Tools + Eclipse IDE
Learn how to use the Hibernate tools is a must!
- Install Hibernate / JBoss Tools in Eclipse IDE
Install Hibernate in your Eclipse IDE. - Generate Hibernate mapping files & annotation with Hibernate Tools
Auto generate Hibernate codes for you.
Hibernate Logging
How to do logging in Hibernate
- Configure logging in Hibernate – SLF4j + Log4j
Integrate SLF4j + Log4j with Hibernate. - Configure logging in Hibernate – Logback
Integrate Logback with Hibernate.
Hibernate Connection Pool
How to configure database connection pool in Hibernate
- Configure C3P0 connection pool in Hibernate
Integrate C3P0 with Hibernate. - Configure DBCP connection pool in Hibernate
Integrate Apache DBCP with Hibernate.
Hibernate Cascade
Hibernate cascade is use to manage the state of the other side automatically.
- Cascade example (save, update, delete and delete-orphan)
Cascade examples in save, update, delete and delete orphan. And the different between delete and delete orphan. - Different between cascade and inverse
Many Hibernate developers are confuse about the different between the cascade and inverse, here’s the explanation. - Cascade – JPA & Hibernate annotation common mistake
A super easy common annotation mistake made by beginner or experienced Hibernate developers – JPA cascade annotation in Hibernate?
Hibernate Query Language (HQL)
Hibernate own language for the data manipulation, it’s quite similar to database SQL language.
- Hibernate Query examples (HQL)
HQL CRUD examples , select, update , delete and batch insert (no single insert support). - Hibernate parameter binding examples
Bind the parameter into HQL with “Named parameters” and “Positional parameters” methods. - How to embed Oracle hints in Hibernate query
A trick to embed the Oracle hints into Hibernate Query to increase the Oracle query performance.
Hibernate Criteria
Hibernate Criteria API is an alternative to Hibernate Query Language (HQL). It’s always a good solution in many optional search criteria.
- Hibernate Criteria examples
Criteria examples – basic query, ordering query, restrictions query and paging the result.
Hibernate Native SQL
In some scenarios, Hibernate HQL or Criteria is just not enough to do what you want, here you can use the native database SQL language directly.
- Hibernate native SQL queries examples
A guide to show how to use native SQL in Hibernate.
Hibernate Named Query
Named Query lets developers put the HQL into XML mapping file or annotation for maintainability purpose, you just do not want all your HQL syntax scatter all over the Java code. ![]()
- Hibernate named query examples
Working with named query in XML file and Annotation.
Hibernate Transaction
All things related to Hibernate Transaction
- Hibernate Transaction handle example
A simple standard example to use Hibernate transaction.
Hibernate Advance Technique
Some Hibernate Advance technique, seldom use but practical skills (data filter and interceptor).
- Hibernate data filter example – XML and annotation
Hibernate data filter is used to filter the retrieve data from database, Here’s a guide to work with data filter in XML or Annotation. - Hibernate interceptor example – audit log
Hibernate interceptor is used to intercept the Hibernate events like CRUD operations, a detail example of audit log implementation with Hibernate interceptor.
Hibernate Performance
Some tweaks will make your Hibernate run faster ![]()
- dynamic-insert attribute example
Using dynamic-insert to avoid the include unmodified properties in the SQL INSERT statement. - dynamic-update attribute example
Using dynamic-insert to avoid the include unmodified properties in the SQL UPDATE statement. - Hibernate mutable example (class and collection)
Using mutable keyword to avoid the generate unnecessary SQL statements. - Hibernate – fetching strategies examples
Hibernate fetching strategies are used to optimize the Hibernate generated select statement, a must learn skill for any Hibernate developers. - Different between session.get() and session.load()
Understanding when should use get or load to retrieve the object in order to avoid unnecessary hit to the database.
Integrate Hibernate with Other Frameworks
Examples to integrate Hibernate with other frameworks.
- Struts + Hibernate Integration
Example to integrate Hibernate with Struts framework. - Struts + Spring + Hibernate Integration
Example to integrate Hibernate with Struts and Spring framework together. - Spring + Hibernate Integration
Example to integrate Hibernate with Spring framework. - Spring + Hibernate Integration (Annotation)
Example to integrate Hibernate with Spring framework (Annotation version).
Hibernate FAQ
Some frequence answer questions :
- How to load hibernate.cfg.xml from different directory
By default, Hibernate looking the hibernate.cfg.xml at the project class path, here’s a guide to load it from specified folder. - How to add Hibernate XML mapping file (hbm.xml) programmatically
A tip to load hibernate.cfg.xml programmatically - List of Hibernate database Dialect
List of the dialect collection for different type of database vendors. - show_sql , format_sql and use_sql_comments
Configure Hibernate to display the generated SQL statement to console. - How to display hibernate sql parameter values – P6Spy
Using P6Sqpy third party library to display the Hibernate SQL parameter value. - How to display hibernate sql parameter values – Log4j
Using Log4j to display the Hibernate SQL parameter value. - How to call store procedure in Hibernate
It’s not recommend to put business logic into store procedure, never mind, you still allow to call store procedure in Hibernate. - How to use database reserved keyword in Hibernate
In some special case, you may need to use the database keyword in your Hibernate class (not recommend), here’s a trick to achieve it. - How to save an image into database
A tutorial to show how to use Hibernate to save an image into database.
Hibernate Common Errors
Here are list of the common errors messages in Hibernate development.
- Unable to insert if column named is keyword, such as DESC
- Hibernate – Could not find C3P0ConnectionProvider
- Hibernate – The type AnnotationConfiguration is deprecated
- java.lang.ClassNotFoundException : javassist.util.proxy.MethodFilter
- Remember that ordinal parameters are 1-based! – Hibernate Template
- org.hibernate.AnnotationException: Unknown Id.generator
- An AnnotationConfiguration instance is required to use
- java.lang.NoClassDefFoundError: org/dom4j/DocumentException
- java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
- java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap
- java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter
- java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources
- java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager
- java.lang.NoClassDefFoundError: antlr/ANTLRException
- java.lang.NoClassDefFoundError: javax/transaction/Synchronization
- java.lang.ClassFormatError : Absent Code attribute in method that is not native or abstract in class file …
- java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter
- java.lang.ClassNotFoundException: javax.persistence.Entity
- java.lang.ClassNotFoundException: javax.transaction.TransactionManager
- java.lang.ClassFormatError : Absent Code attribute in method that is not native or abstract in class file …
Off Topic
- Why i choose Hibernate framework for my project?
The reasons why i like to implement Hibernate in the future project.
Nice tutorial
this tutorial helped me a lot
Best website for hibernate I also want to use some application in my portal and software and now I a can do this Thanks To MKYONG
Thanks mkyong, you are great, hope many people benefited out of this.
Hai Everybody… Special Hai to Mkyong and thanks for making maintaining such a nice site for hibernate.. I am subbu from India, I am working in TATA…
helped a lot
Can you please explain how to use custom generators for sequences
I do trust all of the ideas you have offered to your post. They’re very convincing and will certainly work. Still, the posts are very brief for newbies. May just you please prolong them a bit from next time? Thanks for the post.
Hi,
i am working in maven hibernate project for trade automation testing. here we are facing the difficuties in the hibernate to get the object model to the lazy fetch select Db values to compare part. can you share the relevent examples please.
Hey mkyong, I hope you no where mentioned about unidirectional & bidirectional mapping in this article. Can you please explain what is bidirectional mapping ,how we can make it in hibernate & what is its use?
Congratulations, it’s really a wonderfull site. I have one question about hibernate framework. How can i should to do “join’s” in HQL language? What are configurations and anotations necessary?
Best regards.
Can you help me example about EVENTS in Hibernate. Thanks.
Noted.
[...] out how to achive it but after a deep deep deep digging in google I’ve discovered a great tutorial site with many examples for Hibernate. Moreover the examples on that site are done with the last version [...]
Hi MkYong,
How are you ? i have got a problem with pagination, i did a small project with struts2+spring3+JPA(Hibernate) and i used display tag for pagination, all are working fine, but the problem is this display tag will fetch all the data every time when i click on the page number… now i have may be 1000 records and i don’t feel any problem, what if there is billions of records.. i need to remove this display tag and i want to get requested number of data when i click on the page numbers.. if the 10 records per page is fixed then if i click on 2 then it should get the data from 11 to 20… please if you know about that help me..
thanks a lot, u helped me in the past..
A.R.U
hi arun i want to do same application. i am new with spring ans hibernate.can you please share some code or at least steps in spring an hibernate??
my details:
Email id:- ashish.jadhav29[at]gmail.com
hoping for positive response.
[mkyong edited to avoid email spam]
Refer this series of Spring tutorials.
Great stuff. Explained very nicely. Will visit often for reading.
hi can u post some tutorials related to servlets and JSP
Hey dude
awesome site. love the tutorials: clear, clean, simple, best practices.
thank you.
Hi,
I found this link which explains how to resolve this issue.
http://forums.oracle.com/forums/thread.jspa?messageID=4045926
Hi,
This is by far the best tutorial site I have come across. Thanks for the wonderful information posted.
I was trying out your hibernate example (3.6). One of the downloads for ojdbc jar in pom.xml seems to be broken.
Here’s the error:
Failure to find com.oracle:ojdbc6:jar:11.2.0 in http://repository.jboss.org/nexus/content/groups/public/ was cached in the local repository, resolution will not be reattempted until the update interval of JBoss repository has elapsed or updates are forced.
I think we need to update the pom.xml with the suitable entry to get the jar file.
Cheers,
Suresh S
ojdbc is Oracle jdbc driver, due to license issue, no repository daring to release this jar
.
To fix it, you need to download ojdbc from Oracle, then register it into your local Maven repository manually.
pls give a complete tutorial
how works hiberanate application with a simple example ?
Thanks
Refer to quick start, many simple example with hibernate.
awesome tutorial. Helped me a lot
Hi Mkyong,
Thank you very much?Great posts! I found explainations are to the point, no verbose. great resource for young developers.
I come from china?I often find information in the United States website?I am a university student about to graduate?The site I will introduce it to more students and colleagues
I appreciate your selfless effort?
Thanks for your recommendation, and good to know my articles did help you in some ways
Hi Mkyong,
I think the collection of your tutorials is just great.
If possible can u please add a tutorial on level two caching in hibernate.
Hi,
Can you throw some light on Spring-iBatis technology? I t wil be quite useful for me.And I went throw your spring tutorials, to say the fact, it was ASWEOSME!
Thnaks for such useful tutorials!
Hi Anu,
for iBatis go through iBatis in action book, its very simple to learn ibatis as it is less complicated than Hibernate.
iBatis in large project will caused a maintenance overhead. Actually, both iBatis and Hibernate has their prons and cons, just use it in the right correct, right time…
Hi,
Can you throw some light on Spring – iBatis integration?
Its really a wonderfull tutorial…
Hi
I got one requirement where I am getting the XSDs.I have to use xmlbeans(for pojo class) and save the data by using Hibernate.I am new to both XMLbean and Hibernate.Please share any sample code based on xsds,xmlbean and hibernate.
Thanks in Advance
Hi Yong.
Please write some article about Hibernate, Srtuts 2 and Spring integration.
Also write some good tutorial on Apache Axis (Web Services). This topics are still not covered will on Internet.
Regard
Tousif
Struts2 go here
http://www.mkyong.com/tutorials/struts-2-tutorials/
http://www.mkyong.com/struts2/struts-2-spring-hibernate-integration-example/
Thanks for your idea on Apache Axis, will look into it.
Perfect. Thank You.
Hi.
we need More my friend form this site about hibernate and spring and also new version of technology as jsf materials can kindly set jsf also it possible it use to all the people
you help me and many people, keep on, and thank you a lot for your tutorials
tutorials are awesome
and very very good
Do you have any example based on hibernate return insert?
Ref: http://www.it-eye.nl/weblog/2007/06/12/what-i-would-like-to-see-in-jpa-2/
good tutorials
thank you very much
good tutorials of all framework.
thanks mr.yong
Hi!
I’m Mauro from Buenos Aires. I just write to thank you for your tutorials, great job!
Yong. your tutorial is awesome. Thanks
Hello is there a way to find if the table already exist in database before we create it using hbm files.
I gone through the notes and it is very good for begeers. ~Thanks,jaga
What are three programming languages that you think every programmer should know?
For Java programmer,
1. Struts – Is this dead? Definitely not, there are still thousand of companies using it.
2. Hibernate – Market required, i just cant find alternative of it.
3. Spring – Too flexible and change the way we code.
Knowing the above 3 stuff, you will definitely get a very good paycheck. Mind to share yours?