Hibernate Tutorial

Hibernate tutorials

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.

Hibernate Association (Table Relationship)

How to define table relationship one-to-one, one-to-many, many-to-may in Hibernate.

Hibernate / JBoss Tools + Eclipse IDE

Learn how to use the Hibernate tools is a must!

Hibernate Logging

How to do logging in Hibernate

Hibernate Connection Pool

How to configure database connection pool in Hibernate

Hibernate Cascade

Hibernate cascade is use to manage the state of the other side automatically.

Hibernate Query Language (HQL)

Hibernate own language for the data manipulation, it’s quite similar to database SQL language.

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 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 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 Transaction

All things related to Hibernate Transaction

Hibernate Advance Technique

Some Hibernate Advance technique, seldom use but practical skills (data filter and interceptor).

Hibernate Performance

Some tweaks will make your Hibernate run faster πŸ™‚

Integrate Hibernate with Other Frameworks

Examples to integrate Hibernate with other frameworks.

Hibernate FAQ

Some frequence answer questions :

Hibernate Common Errors

Here are list of the common errors messages in Hibernate development.

Off Topic

Hibernate References

123 comments on “Hibernate Tutorial

  1. 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

    Reply
  2. Bit late here, but all hibernate tutorials contain deprecated APIs. Lots have been changed since hibernate > 4

    Reply
  3. 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 πŸ™‚

    Reply
  4. Hi Sir could you post an example for self join(one-to-many) with create and select operation

    Reply
  5. hi sir,
    i want to perform simple crud hibernate + mongoDB Any idea????

    Reply
  6. 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.

    Reply
  7. 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

    Reply
  8. 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;

    Reply
  9. 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.

    Reply
  10. Hii folks i am getting this error while using hibernate with jpa…”java.lang.ClassNotFoundException: org.hibernate.integrator.spi.Integrator”thanx in advance

    Reply
  11. 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.

    Reply
  12. 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

    Reply
  13. 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

    Reply
    1. Mostly used for Null pointer exception
      eg: request.getParameter(“”)==null?1:2

      Reply
  14. Hi mkyoung
    can u please provide tag example , it is required . please help me , thanks in advance

    Reply
  15. is it possible to execute a sql query with the help of hibernate

    Reply
    1. You can execute sql queries by createSQLQuery method in hibernate

      Reply
  16. i have doubt is it possible to execute a sql query with the help of hibernate

    Reply
    1. 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();

      Reply
  17. you can find some more details in the below link,”http://javadomain.in/multiple-databases-using-hibernate-example/”

    Reply
  18. Hi , BuildSessionFactory also deprecated , so i think its better explain about it also..Thank you

    Reply
  19. how to set the default values in SimpleFormController in spring mvc?

    Reply
  20. how to resolve org.hibernate.LazyInitialiazationException?

    Reply
  21. hello sir your java/j2ee concepts r really useful & powerful.thanq very much sir

    Reply
  22. Hi MK,

    Great tutorials always ! I am waiting for hibernate annoatation configuration with entity manager configuration tutorials. I am having some issues in the entity manager configuration.

    πŸ™‚

    Thanks !
    Rahul

    Reply
  23. Hi Yong,

    Hope u r fine. I need 1 help. I want to configure multiple database using Spring nd Hibernate. Can u help me in this please.

    I will wait for ur valuable reply to my mail.

    Thanks
    Ravi

    Reply
  24. Thanks Mkyong team for the tutorials. Can you please add an example for Hibernate “Session in view pattern”(Extended Session). I guess this is used in many real time projects. Could find any good examples like yours . Can you enlighten us on this.

    Reply
  25. Please help me.. can you explain more in hibernate, if i want to use annotation, but using persistence.xml on my config (not use hibernate.cfg.xml and hbm.xml).

    Reply
  26. i want Hibernate Pagination example in java which shows results in jmesa on jsp.
    please help me

    Reply
  27. hey, thanks for the excellent collection of Hibernate collection.
    I have no idea about Maven still able to run all the examples in eclipse.

    Thank you so much!

    Reply
  28. hi sir,
    how to fix the org.hibernate.SQLGrammer Exception:could not update next value

    Reply
  29. Sir,

    can you please post some examples of caching with hibernate.
    That would really help.. either with ehcache/ OSCache.??

    and its usage in a distributed env.
    Thank you.

    Reply
  30. Hi,

    Could you please show an example of using JAX-RS and Spring and Hibernate Example. I followed your JAX-RS and Spring example and it worked liked a charm. Now i want to add JPA to this. Could you please upload an example of doing this.

    Reply
  31. What is the use of SessionFactory class object in Hibernate?

    Reply
    1. sessionfactory the name itself says its a factory…

      It is used for creating the objects for session..

      Reply
    2. SessionFactory sessionFactory=config,.buildSessionFatory();

      It is heavy weight Component.By using that class object we can create sessions.

      Reply
    3. SessionFactory is an interface and SessionFactoryImpl is its implementing class. It is SessionFactory which load entire configuration file. All data in configuration file are loaded into a variable and thse variable group together are high level Hibernate object or we can say SessionFactory. SessionFactory is responsible for opening session.

      Reply
  32. I’m new in all of this, I have to debug an interface which extract data from a PostgreSQL Database.
    Correct code from stranger is hard, even more when you discover some new concept.
    Your tutorial help me a lot.
    Thank you.

    Reply
  33. Hi Sir,
    I have gone through the hibernate documentation and I found some term like Proxy its difficult to understand .And I have doubt on cache starategy ,locking strategy and flushing strategy ..can u please add one one section on that..If u explain all enum constant of CacheMode,LockMode,FetchMode its help full for us….

    Reply
  34. Hi Sir,
    I have gone through the hibernate documentation and I found some term like Proxy its difficult to understand .And I have doubt on cache starategy ,locking strategy and flushing strategy ..can u please add one one section on that..If u explain all enum constant of CacheMode,LockMode,FetchMode its help full for us….

    Reply
  35. hi, mkyong……
    ..your’s tuturials is quite good and helpful……….
    1)would you expalin me inherintance in hibernate with examples?
    2)and what is session factory in hibernate…..would you expalin me in details?
    3)and what is dirty checking in hibernate?

    Reply
    1. session.isDirty() method is used to check whether some data is still pending to be flushed to Database or not. If you call session.flush(); first then isDirty() method will return false.
      SessionFactory is an interface and SessionFactoryImpl is its implementing class. It is SessionFactory which load entire configuration file. All data in configuration file are loaded into a variable and thse variable group together are high level Hibernate object or we can say SessionFactory. SessionFactory is responsible for opening session.

      Reply
  36. sir plz help me πŸ™‚ . i am using both spring mvc and hibernate .
    plz tell me how to retrive an innerjoined hql quary in hibernate to a jsp view page .
    also tell me how to retrive data to list box by the help of hibernate and spring mvc (refrenceData)method, i want to save data(id) from the list box too.

    Reply
    1. sir , i want to use spring mvc controller class’s to collect data from and to hibernate then to database .

      Reply
  37. Hello Sir,
    Surfing your site from 1 month… Liked it…
    i need 1 example on MVC…. it should not contain Spring, Struts or any other frame work. i require just JSP, JAVA Beans Example… Could you please help…

    Reply
    1. You shouldn’t redesign the new MVC framework, it take much time to solve something that already solved.

      Reply
    2. Mr.J, Check out Struts design and programming by Budi Kurniawan. 1st chapter has got that kind of example.

      Reply
  38. Respected MkYong Sir,

    how is the right way to mapping multilingual data tables to entities?

    Example:
    Tables: Countries Languages
    and manages Countries and Countriesi18n with one entity (Country)

    Hoping for your response.

    Thx

    Reply
  39. Hello Yong,

    I was trying to make a web service with Restful architecture using RestEasy framework and JAX-RS. Also integrated it with Spring. Till this time all the code ran fine…and response was coming.

    But when i tried to integrate Hibernate in it…and when i run my Jboss server,deployment of war file fails…

    And same code of Hibernate runs fine when i try to hit method by main() ..just tested for demo,

    Reply
  40. Hi Sir,

    I am Niranjan panigrahi
    i need uour help.
    1.can you please explain about the cascade attribute
    and i want (on delete cascade) mechanism by doing something like this
    cascade=’cascade-all’ but it is not working

    2.
    My requirement is to implement Composite Unique
    (ie i want to make the combination of username
    and password as unique.to fulfill my requirement I used component , is there any other way ?

    Reply
  41. Respected MkYong Sir,

    I am new to hibernate. I have used Struts 1.3,JSP,Servlet etc..Now i am going to learn hibernate. I have taken so many times help from this site. But currently i am confuse about which version should i learn ? And also sir can You provide some example with Netbeans IDE instead Eclipse because i generally used Netbeans IDE.

    Hoping for your response.

    Thanks

    Reply
    1. For Hibernate, study 3.6 will do, industry take time to migrate to version 4. But Struts 1.3 is a bit too old, try study Struts 2 or other web application to improve your skill, prepare for next jump πŸ™‚

      Even all projects are developed under Eclipse, but all follow Java standard, you should be able to import it into NetBean easy. Personally, i don’t like Netbean’ UI and performance, so Netbean example will be impossible, at this moment.

      Reply
      1. Thanks a lot sir for suggestions.

        ya i have imported Eclipse projects in Netbeans so many times as netbeans provide import facility.
        Ya now onwards i use Eclipse,

        Thanks again sir.

        Reply
  42. what are the difference among HibernateUtil.getSessionFactory(), HibernateUtil.getCurrentSession(), HibernateUtil.openSession() ?

    Reply
  43. 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?

    Reply
  44. Hi! These articles will be updated for the new version??
    Some methods have become deprecated….

    Reply
    1. Thanks for your suggestion, Hibernate is updated to version 4, will update in future.

      Reply
  45. The information on this site is very useful. I bookmarked this website and always read topics on this site before i search in google. I shared this site with many friends. Every concept with example and clarity is very nice. We need our authors to follow this pattern rather 1000 sleeping pages with vague explaination.

    Gubs

    Reply
  46. 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

    Reply
  47. Thanks mkyong, you are great, hope many people benefited out of this.

    Reply
  48. 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…

    Reply
  49. Can you please explain how to use custom generators for sequences

    Reply
  50. 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.

    Reply
  51. 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.

    Reply
  52. 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?

    Reply
  53. 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.

    Reply
  54. 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

    Reply
    1. 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]

      Reply
  55. Great stuff. Explained very nicely. Will visit often for reading.

    Reply
  56. hi can u post some tutorials related to servlets and JSP

    Reply
  57. Hey dude

    awesome site. love the tutorials: clear, clean, simple, best practices.

    thank you.

    Reply
  58. 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

    Reply
    1. 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.

      Reply
  59. 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?

    Reply
    1. Thanks for your recommendation, and good to know my articles did help you in some ways πŸ™‚

      Reply
  60. 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.

    Reply
  61. 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!

    Reply
    1. Hi Anu,
      for iBatis go through iBatis in action book, its very simple to learn ibatis as it is less complicated than Hibernate.

      Reply
      1. 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…

        Reply
  62. 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

    Reply
  63. 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

    Reply
  64. 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

    Reply
  65. you help me and many people, keep on, and thank you a lot for your tutorials

    Reply
  66. Hi!
    I’m Mauro from Buenos Aires. I just write to thank you for your tutorials, great job!

    Reply
  67. Hello is there a way to find if the table already exist in database before we create it using hbm files.

    Reply
  68. I gone through the notes and it is very good for begeers. ~Thanks,jaga

    Reply
  69. What are three programming languages that you think every programmer should know?

    Reply
    1. 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?

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *