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.
what are the difference among HibernateUtil.getSessionFactory(), HibernateUtil.getCurrentSession(), HibernateUtil.openSession() ?
Hi sir,I have done insert update delete using your jsf integration with spring and hibernate project but how can i search the values from database ?If am giving customerid then showing about that name and address in text box and textarea.
nice tutorial..its an easy to understand each steps
Hi
We have a web app using hibernate 3 and a sql server 2008 database.
we have a table with query timeouts due to a deadlock caused users accesing the table at once when the query is called from the web app and also when I run the query in sql server it runs forever without returning data. So I ran the query in sql server with “with (no lock)” e.g “select * from Table table with(nolock) where (criteria)…” and it works perfectly….BUT when put “with (no lock)” in the query of my DAO implementation as follows:
sql.append(“select count(*)”);
sql.append(” from Table item with(nolock)”);
sql.append(” where item.Id = ? “);
params.add(Id);
sql.append(” and item.status in(0,1,2,3)”);
Collection data = getHibernateTemplate().find(sql.toString(),
params.toArray());
I get this error:
ERROR 12:41:01 org.hibernate.hql.PARSER line 1:48: unexpected token: with
Why is this causing a problem? What can I do to fix it?
Your help is greatly appreciated
you can find some more details in the below link,”http://javadomain.in/multiple-databases-using-hibernate-example/”
how to set the default values in SimpleFormController in spring mvc?
Hi Yong,
Is it possible to insert multiple records into child table but not in a single go(One to Many Mapping).
My parent table will always have one record,but my child table can have multiple records.
Pls.note not in a single go(I mean multiple requests to insert data into child table).
If possible,can you pls. share the example for the same?
Any help on the above issue…..
The content of element type “class” must match “(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|
composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-
component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-
subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,fetch-profile*,resultset*,(query|sql-query)*)”. i am getting this error while doing this could you please explain me how to solve it
Bit late here, but all hibernate tutorials contain deprecated APIs. Lots have been changed since hibernate > 4
Hi sir,
I want to create a simple human resource application using hibernate framework. Are there any sample projects available on those? im new to hibernate. Any help would be highly appreciated. Thank you 🙂
Hi Sir could you post an example for self join(one-to-many) with create and select operation
hi sir,
i want to perform simple crud hibernate + mongoDB Any idea????
sir,
i always follows your site… and your site helps me a lot many time… but dis time I see that you used all your example project using oracle 11g … plz. tell me is it cause any problem with oracle 10g??? actually I’ve to do the following work with oracle 10g
1) Retrieve some data programmatically from .stl file(Almost a text file)
2) Then insert the retrieved data into 3 tables of oracle10g using hibernate
HIbernate Distributed transaction Example please.
HI,
Please help me for below situation.
I have tables like:
CREATE TABLE “OTHER_ACTIVITY_DETAIL”
( “SNO” NUMBER NOT NULL ENABLE,
“OA_DEVELOPER” NUMBER NOT NULL ENABLE,
“OA_DATE” DATE,
“OA_TYPE” VARCHAR2(2) NOT NULL ENABLE,
“OA_EFFORT” NUMBER,
“OA_REMARKS” VARCHAR2(200),
“OA_PREDEFINE” VARCHAR2(4),
“ACCOUNT_CODE” VARCHAR2(5) NOT NULL ENABLE,
CONSTRAINT “OTHER_ACTIVITY_DTL_PK” PRIMARY KEY (“SNO”) ENABLE
)
** Note: OA_PREDEFINE may null in my situation.
CREATE TABLE “PRE_DEFINE_ACTIVITY”
( “SNO” NUMBER NOT NULL ENABLE,
“PRE_DEFINE_CODE” VARCHAR2(4) NOT NULL ENABLE,
“PRE_DEFINE_DESC” VARCHAR2(50),
“PRE_DEFINE_MONTH” DATE,
“ACCOUNT_CODE” VARCHAR2(5) NOT NULL ENABLE,
CONSTRAINT “PRE_DEFINE_ACTIVITY_PK” PRIMARY KEY (“SNO”) ENABLE
)
I used in hbm like :
Please help me to prepare HQL.
I am using Spring 4+ Hibernate 4 please suggest me how to achieve in XML mapping way.
Thanks,
Venkat.
CREATE OR REPLACE TRIGGER “MCDEV”.”BI_MC_TBL_PRE_DEFINE_ACTIVITY”
before insert on “MC_TBL_PRE_DEFINE_ACTIVITY”
for each row
begin
select “MC_TBL_PRE_DEFINE_ACTIVIT_SEQ”.nextval into :NEW.SNO from dual;
end;
/
ALTER TRIGGER “MCDEV”.”BI_MC_TBL_PRE_DEFINE_ACTIVITY” DISABLE;
Hello. I’m a Korean Student Studying Hibernate. Whenever I google Spring or Java and Hibernate. I found your blog’s Articles. Everytime. Thanks a million. Your tutorial is very helpful for me.
Thanks a lot
Hii folks i am getting this error while using hibernate with jpa…”java.lang.ClassNotFoundException: org.hibernate.integrator.spi.Integrator”thanx in advance
Hello, I have a scenario, where i have to fetch parent table with specific childs (not all). for example, table A has one to one relationship with table B and C.I want to fetch table A data with table B only (not C). Do we have any configuration for the same. Other approach we thought was to remove mapping and fetch A and B using left join. but looks like HQL doesn’t support left join on independent tables. can you please suggest.
Thanks in advance.
Hi Sir,
i am using session to write a bulk of entities to DB in first 3 hours i have
dumping rate around 2500 record per minute but after that the rate go down to
be 100 records per minute
Java ternary operator
Mostly used for Null pointer exception
eg: request.getParameter(“”)==null?1:2
Hi mkyoung
can u please provide tag example , it is required . please help me , thanks in advance
Thanks for sharing. You’ve saved me days of Googling effort.
I always read your blogs and tutorials.
is it possible to execute a sql query with the help of hibernate
You can execute sql queries by createSQLQuery method in hibernate
i have doubt is it possible to execute a sql query with the help of hibernate
Yes We can execute a sql query with the help of hibernate
Query query = session.createSQLQuery(“Write Query here”);
//If some parameter to be passed
query.setParameter(0,value1);
List list = query.list();
Superb…. Boss
Hi , BuildSessionFactory also deprecated , so i think its better explain about it also..Thank you
how to resolve org.hibernate.LazyInitialiazationException?
hello sir your java/j2ee concepts r really useful & powerful.thanq very much sir