Professional Documents
Culture Documents
the possible values for the hbm2ddl configuration property are the following ones:
create-drop - The database schema will be dropped and created afterward. Upon closing
the SessionFactory, the database schema will be dropped.
validate - The database schema will be validated using the entity mappings.
update - The database schema will be updated by comparing the existing database schema with
the entity mappings.
The hibernate.hbm2ddl.auto="update" is convenient but less flexible if you plan on adding functions or
executing some custom scripts.
Hibernate: Hibernate is a framework which is used to develop persistence logic which is independent of
Database software. In JDBC to develop persistence logic we deal with primitive types. Whereas
Hibernate framework we use Objects to develop persistence logic which are independent of database
software.
Hibernate Architecture:
Configuration:
cfg.configure();
If the config file is not valid then it will throw an exception. If it is valid then it creates a meta-
data in memory and returns the meta-data to object to represent the config file.
SessionFactory:
From cfg object it takes the JDBC information and create a JDBC Connection.
SessionFactory factory=cfg.buildSessionFactory();
Session:
Session is an interface which is present in org.hibernate package. Session object is created based
upon SessionFactory object i.e. factory.
Session session=factory.buildSession();
Transaction:
Transaction object is used whenever we perform any operation and based upon that operation
there is some change in database.
Transaction object is used to give the instruction to the database to make the changes that
happen because of operation as a permanent by using commit() method.
Transaction tx=session.beginTransaction();
tx.commit();
Query:
This interface exposes some extra functionality beyond that provided by Session.iterate() and
Session.find():
Query query=session.createQuery();
Criteria:
The Session is a factory for Criteria. Criterion instances are usually obtained via the factory
methods on Restrictions.
Criteria criteria=session.createCriteria();
In Hibernate, we can either create a new object of an entity and store it into the database, or we can
fetch the existing data of an entity from the database. These entity is connected with the lifecycle and
each object of entity passes through the various stages of the lifecycle.
1. Transient State
2. Persistent State
3. Detached State
4. Removed State
Hibernate Lifecycle
As depicted from the above media one can co-relate how they are plotted in order to plot better in our
mind. Now we will be discussing the states to better interpret hibernate lifecycle. It is as follows:
The transient state is the first state of an entity object. When we instantiate an object of a POJO
class using the new operator then the object is in the transient state. This object is not connected with
any hibernate session. As it is not connected to any Hibernate Session, So this state is not connected to
any database table. So, if we make any changes in the data of the POJO Class then the database table is
not altered. Transient objects are independent of Hibernate, and they exist in the heap memory.
1. When objects are generated by an application but are not connected to any session.
Here, we are creating a new object for the Employee class. Below is the code which shows the
initialization of the Employee object :
e.setId(21);
e.setFirstName("Neha");
e.setMiddleName("Shri");
e.setLastName("Rudra");
Once the object is connected with the Hibernate Session then the object moves into the Persistent
State. So, there are two ways to convert the Transient State to the Persistent State :
1. Using the hibernated session, save the entity object into the database table.
2. Using the hibernated session, load the entity object into the database table.
In this state. each object represents one row in the database table. Therefore, if we make any changes in
the data then hibernate will detect these changes and make changes in the database table.
session.persist(e);
session.save(e);
session.saveOrUpdate(e);
session.update(e);
session.merge(e);
session.lock(e);
Example:
// Transient State
//Persistent State
session.save(e);
For converting an object from Persistent State to Detached State, we either have to close the session or
we have to clear its cache. As the session is closed here or the cache is cleared, then any changes made
to the data will not affect the database table. Whenever needed, the detached object can be
reconnected to a new hibernate session. To reconnect the detached object to a new hibernate session,
we will use the following methods as follows:
merge()
update()
load()
refresh()
save()
update()
session.detach(e);
session.evict(e);
session.clear();
session.close();
// Transient State
// Persistent State
session.save(e);
// Detached State
session.close();
In the hibernate lifecycle it is the last state. In the removed state, when the entity object is deleted from
the database then the entity object is known to be in the removed state. It is done by calling the delete()
operation. As the entity object is in the removed state, if any change will be done in the data will not
affect the database table.
Example
// Transient State
Session s = sessionfactory.openSession();
e.setId(01);
// Persistent State
session.save(e)
// Removed State
session.delete(e);
In this case the hibernate will fire select query only the first time and in second time since it needs the
already retrieved object,it will look for it in Session cache.
Here hibernate wont even fire select query while fetching Student object,rather it will provide us with
proxy object.It will only access db to fetch the method called – here getname().
create the hibernate application with Annotation
Here, we are going to create a maven based hibernate application using annotation in eclipse IDE. For
creating the hibernate application in Eclipse IDE, we need to follow the below steps:
o To create the maven project left click on File Menu - New- Maven Project.
o The new maven project opens in your eclipse. Click Next.
o Now, select catalog type: internal and maven archetype - quickstart of 1.1 version. Then, click
next.
o Now, specify the name of Group Id and Artifact Id. The Group Id contains package name (e.g.
com.javatpoint) and Artifact Id contains project name (e.g. HibernateAnnotation). Then click
Finish.
2) Add project information and configuration in pom.xml file.
Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag. These dependencies are used to add the jar files in Maven
project.
1. <dependency>
2. <groupId>org.hibernate</groupId>
3. <artifactId>hibernate-core</artifactId>
4. <version>5.3.1.Final</version>
5. </dependency>
6.
7. <dependency>
8. <groupId>com.oracle</groupId>
9. <artifactId>ojdbc14</artifactId>
10. <version>10.2.0.4.0</version>
11. </dependency>
Due to certain license issues, Oracle drivers are not present in public Maven repository. We can install it
manually. To install Oracle driver into your local Maven repository, follow the following steps:
o Install Maven
Here, we are creating the same persistent class which we have created in the previous topic. But here,
we are using annotation.
@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use
@Table annotation, hibernate will use the class name as the table name by default.
@Column annotation specifies the details of the column for this property or field. If @Column
annotation is not specified, property name will be used as the column name by default.
To create the Persistence class, right click on src/main/java - New - Class - specify the class name with
package - finish.
Employee.java
1. package com.javatpoint.mypackage;
2.
3. import javax.persistence.Entity;
4. import javax.persistence.Id;
5. import javax.persistence.Table;
6.
7. @Entity
8. @Table(name= "emp500")
10.
11. @Id
14.
17. }
20. }
23. }
26. }
29. }
32. }
33. }
To create the configuration file, right click on src/main/java - new - file - specify the file name (e.g.
hibernate.cfg.xml) - Finish.
hibernate.cfg.xml
4. "http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">
5. <hibernate-configuration>
6. <session-factory>
7.
8. <property name="hbm2ddl.auto">update</property>
9. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
14.
16. </session-factory>
17. </hibernate-configuration>
StoreData.java
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.Metadata;
7. import org.hibernate.boot.MetadataSources;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10.
11.
14.
17.
21.
23. e1.setId(101);
24. e1.setFirstName("Gaurav");
25. e1.setLastName("Chawla");
26.
27. session.save(e1);
28. t.commit();
30. factory.close();
31. session.close();
32.
33. }
34. }
Before running the application, determine that the directory structure is like this.