Hibernate is the most-popular persistence framework and ORM tool for Java Applications. ORM (Object/Relational Mapping) is a methodology where objects in Java Applications are persisted transparently in the relational database tables. ORM uses metadata which describes the mapping between classes & tables, instances & table rows and instance properties & table columns. Under the hood, Hibernate works by transforming data from one representation to another.
This Hibernate 4 Tutorial series based on Hibernate 4.3.6.Final
.
For Spring Boot, please refer to our Spring Boot tutorials.
For Spring 4 MVC, please refer to our Spring 4 MVC tutorials.
For Spring 4, please refer to our Spring 4 MVC tutorials.
For Spring 4 Security, please refer to our Spring 4 Security tutorials.
For Spring Batch, please refer to our Spring Batch tutorials.
For AngularJS, please refer to our AngularJS tutorials.
Hibernate MySQL Maven Hello World Example (XML)
Hibernate MySQL Maven Hello World Example (Annotation)
Hibernate One To One Annotation Unidirectional with Shared Primary Key
Hibernate One To One Annotation Unidirectional with Foreign Key Associations
Hibernate One To One Annotation Bidirectional with Shared Primary Key
Hibernate Many To One Annotation Unidirectional
Hibernate Many To One Annotation Bidirectional
Hibernate Many To Many Annotation Unidirectional
Hibernate Many To Many Annotation Bidirectional
In layman’s terms, Hibernate sits between your application and database and provide the persistence for your application via set of API’s, performing transformation(based on defined metadata) transparently between java objects and database representation.
Hibernate functionality/flow/usage can be described as follows:
Below is the brief description of commonly used core API’s in a typical application persistence with Hibernate.
org.hibernate.cfg.Configuration
)It allows the application on startup, to specify properties and mapping documents to be used when creating a SessionFactory. Properties file contains database connection setup info while mapping specifies the classes to be mapped.
org.hibernate.SessionFactory
)It’s a thread-safe immutable object created per database & mainly used for creating Sessions.It caches generated SQL statements and other mapping metadata that Hibernate uses at runtime.
org.hibernate.Session
)It’s a single-threaded object used to perform create, read, update and delete operations for instances of mapped entity classes. Since it’s not thread-safe, it should not be long-lived and each thread/transaction should obtain its own instance from a SessionFactory.
org.hibernate.Transaction
)It’s a single-thread object used by the application to define units of work. A transaction is associated with a Session. Transactions abstract application code from underlying transaction implementations(JTA/JDBC), allowing the application to control transaction boundaries via a consistent API. It’s an Optional API and application may choose not to use it.
org.hibernate.Query
)A single-thread object used to perform query on underlying database. A Session is a factory for Query. Both HQL(Hibernate Query Language) & SQL can be used with Query object.
org.hibernate.Criteria
)It is an alternative to HQL , very useful for the search query involving multiple conditions.
As mentioned above, the very first task a typical Hibernate application does , is it creates the Configuration Object which will eventually create SessionFactory. Configuration Object needs information pertaining to database connection & mapping(XML or Annotations). There are several approaches to provide this information to Hibernate:
1) Using only hibernate.cfg.xml
hibernate.cfg.xml is a standard XML file containing database connection information along with mapping information.This file needs to be found on root of application classpath. Shown below is a sample hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">myuser</property> <property name="hibernate.connection.password">mypassword</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/websystique</property> <property name="show_sql">true</property> <property name="format_sql">false</property> <mapping resource="com/websystique/hibernate/model/Student.hbm.xml"/> <!--<mapping class="com.websystique.hibernate.model.Student"/>--> </session-factory> </hibernate-configuration>
dialect
property informs hibernate to generate database specific (MySQL here) instructions. driver_class
defines the database specific driver hibernate will use to make connection. username,paswwrod & url are general connection properties, nothing special. show_sql
will instruct hibernate to log all the statements on console and format_sql
instructs it to display properly formatted sql. mapping
tag instructs hibernate to perform mapping for mentioned resources(in case of XML Mapping) or classes(in case of Annotation mapping).
Assuming that hibernate.cfg.xml is created for your application and placed in application classpath, SesstionFactory(& Session) can be created as follows:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession();
2) Using hibernate.properties
hibernate.properties is a standard Property file containing database connection information.In this case, you can provide mapping information directly while creating Configuration Object. Shown below is a sample hibernate.properties file
hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.username=myuser hibernate.connection.password=mypassword hibernate.connection.url= jdbc:mysql://localhost:3306/websystique hibernate.show_sql=true hibernate.format_sql=true
Assuming that hibernate.properties file is created for your application and placed in application classpath, SesstionFactory(& Session) can be created as follows:
Configuration cfg = new Configuration().addResource("Student.hbm.xml").addResource("University.hbm.xml"); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession();
In case you are using annotation mapping, above code will as follows:
Configuration cfg = new Configuration() .addClass(com.websystique.hibernate.model.Student.class) .addClass(com.websystique.hibernate.model.University.class); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession();
3) Using Only Programmatic Configuration
In case you don’t want to retain hibernate.properties file(not a good idea though), you can specify everything programatically.
Above configuration will look like:
Configuration cfg = new Configuration() .addClass(com.websystique.hibernate.model.Student.class) .addClass(com.websystique.hibernate.model.University.class). .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect") .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver") .setProperty("hibernate.connection.username", "myuser"); .setProperty("hibernate.connection.password", "mypassword") .setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/websystique") .setProperty("hibernate.show_sql", "true") .setProperty("hibernate.format_sql", "true"); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession();
That was it. Now that you got to know Hibernate fundamentals, check out Hibernate MySQL Maven Hello World Example (XML) to get your hands dirty with a fully working hibernate application example.
View Comments
Hey,
The moment we've all been waiting for is finally here – GoBuildr is now LIVE! 🎉
🌐 Create ultra-lightning-fast websites, sales funnels, eCommerce stores, and more in less than 60 seconds, with just a keyword!
🚀 Say goodbye to the limitations of traditional page builders. GoBuildr combines the functionality of 16 different tools into one powerful app, supercharged with AI-assisted technology.
⇒ Click Here To Checkout Demo https://ext-opp.com/GoBuildr
Which hole you eating first? http://prephe.ro/Vlqn
I just wanna know what would you do to me [OC] http://prephe.ro/Bdsn
Waiting patiently for you to come home and fuck me! https://bit.ly/3UKFVxa
Hi Websystique,
Please share the discussion about internals to Second Level Cache.
If you share the blog I would be very helpful.
Hi Websystique,
It's been a while since we spoke. I need to create a powerful search engine using your java config Spring MVC Hibernate example you generously shared with us.(File upload). Is it possible to include ecache in your java configuration to search for uploaded files? Any examples or advise would be appreciated.
Hi Websystique,
Thanks for the great work. Using hibernate Criteria like the one you used in your Spring 4 file upload, how do you write a dao method to retrieve data from two tables? (OneToMany), How do you write the implementation when implementing the dao interface? Will be great to hear from you.
Hey Andy,
Sorry for late reply.
This Post will help you.
Let me know if you need more help.