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
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:
- On Application startup, hibernate reads it configuration file(hibernate.cfg.xml or hibernate.properties) which contains information required to make the connection with underlying database and mapping information. Based on this information, hibernate creates Configuration Object , which in turns creates SessionFactory which acts as singleton for the whole application.
- Hibernate creates instances of entity classes.Entity classes are java classes which are mapped to the database table using metadata(XML/Annotaitons).These instances are called transient objects as they are not yet persisted in database.
- To persist an object, application ask for a Session from SessionFactory which is a factory for Session.Session represent a physical database connection.
- Application then starts the transaction to make the unit of work atomic, & uses Session API’s to finally persist the entity instance in database.Once the entity instance persisted in database, it’s known as persistent object as it represent a row in database table.Application then closes/commits the transaction followed by session close.
- Once the session gets closed , the entity instance becomes detatched which means it still contains data but no more attached to the database table & no more under the management of Hibernate. Detatched objects can again become persistent when associated with a new Session, or can be garbage collected once no more used.
Below is the brief description of commonly used core API’s in a typical application persistence with Hibernate.
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.
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.
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.
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.
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.
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.