Lesson 5 - Hibernate
Lesson 5 - Hibernate
Lesson 5 - Hibernate
Let's start by discussing why we need Hibernate and why it was created?
Think Through!
MySQL
The USER and the BILLING RECORDS data needs to be stored in DBMS. For this, the user class has to
be mapped to user table, and the Billing Records has to be mapped to the BillingRecords table.
BILLING RECORDS
USER
Scenario 2: Billing Record
CLASS REPRESENTATION
• Association: Java can use association by having another class variable as member; in SQL, no standard
concept is available to represent association
BILLING RECORDS
USER
• In USER table, id is the primary key. This is a foreign key for BILLINGRECORD table.
• It is difficult to change id; we need to update not only the id column in USER, but also the foreign key
column in BILLINGRECORD
• Surrogate key isn’t presented to the user and is only used for identification of data inside the software
system
Scenario 2: Billing Record
ADDING SURROGATE KEY COLUMN: RELATED PROBLEMS
• user_surroagte_id and account_number_id are system generated values. It is difficult to decide whether these
columns should be added to data model or not.
• Different persistence solutions have chosen different strategies. This can cause confusion.
What is the Solution?
Hibernate provides Object Relational Mapping, which takes care of these issues.
Advanced Java
Topic 2—ORM and its Features
ORM
ORM refers to the automated (and transparent) persistence of objects in a Java application to the tables in a
relational database, using metadata that describes the mapping between the objects and the database.
Mapping
• You can support different database management systems by adopting ORM. It provides portability
ORM: Features
• By mapping between logical business model and physical storage model, ORM implements domain
model pattern
• Surrogate key, Identifier, and other key features can be automated in ORM
ORM Architecture
Java Application
Mapping Information
ORM Engine: facilitates creation of mapping information
Reference : http://hibernate.org/orm/
Hibernate Configuration Files
DBMS-specific details and mapping file details are specified in hibernate.cfg.xml and mappingfile.xml.
Hibernate engine uses these files to generate DBMS-specific SQL syntax.
Hibernate
hibernate.cfg.xml
Database Management
Java Application
System
mappingfile.hbm.xml
Features of Hibernate ORM
• Hibernate ORM provides its own native API, in addition to full JPA (Java Persistence API) supports.
• It maps Java POJO’s (Plain Old Java Object ) to relational database.
• It provides rich tool set.
• Performance: Fetch strategies, caching, byte code enhancement
• It is part of JBoss community.
• Java EE 5.0 platform provides a standard persistence API named JPA. As part of the EJB 3.0
specification effort, it is supported by all major vendors of the Java industry.
• Hibernate persistence provider can be used in any environment of Java platform, Java SE or Java EE.
Hibernate Programming Model
Transaction Factory
JNDI
Session Factory
Connection Provider
Transaction JTA
Session object is created within the Database Layer in every DAO method. It is known as persistence
object.
1. Transient: An object is transient if it has just been instantiated using the new operator, and it is not
associated with a Hibernate Session.
2. Persistent: A persistent instance has a representation in the database and an identifier value. It
might just have been saved or loaded; however, it is by definition in the scope of a Session.
3. Detached: A detached instance is an object that has been persistent, but its Session has been
closed. The reference to the object is still valid, of course, and the detached instance might even be
modified in this state.
Hibernate Core APIs
• Loads mapping file and configuration file into memory and makes them available to hibernate engine
• Acts as factory to create the SessionFactory
2. SessionFactory (org.hibrnate.SessionFactory)
3. Session (org.hibernate.Session)
4. Transaction (org.hibernate.Transaction)
The application programmer may create one's own generator classes by implementing the
IdentifierGenerator interface.
• assigned: Default, value has to be explicitly assigned to persistent object before persisting it.
<generator class = assigned/>
• increment: It increments value by 1. It generates short, int, or long type identifier.
• native: It uses identity, sequence, or hilo, depending on the database vendor.
• sequence: It uses the sequence of the database. If there is no sequence defined, it creates a
sequence automatically. For example, in case of Oracle database, it creates a sequence named
HIBERNATE_SEQUENCE.
• hilo: It uses high and low algorithm to generate the id of type short, int, and long.
• identify: It is used in Sybase, My SQL, MS SQL Server, DB2, and SQL to support the id column.
The returned id is of type short, int, or long.
Advanced Java
Topic 4—Setting up a Project with Hibernate
Setting Up a Project with Hibernate
1. Create a Java project and add required jars from the required folder of hibernate downloads
2. Add ojdbc14.jar or mysqlconnector.jar depending on the SQL vendor you are connecting to
3. Create the POJO class and save it in src folder
4. Create the hibernate.cfg.xml file in src folder(configuration file) with specific RDBMS dialect
RDBMS Dialect
Oracle9i org.hibernate.dialect.Oracle9iDialect
Oracle10g org.hibernate.dialect.Oracle10gDialect
MySQL org.hibernate.dialect.MySQLDialect
DB2 org.hibernate.dialect.DB2Dialect
Create the
ClassName.hbm.xml file in src
folder (mapping file)
Create the
ClassName.hbm.xml file in src
folder (mapping file)
Add ojdbc14.jar or
mysqlconnector.jar depending
on the SQL vendor you are class Student
connected to
{
Create the POJO class and save private int rollNo ;
it in src folder
private String name;
Create the hibernate.cfg.xml
file in src folder (configuration // setter menthods
file)
//getter methods
Create the
ClassName.hbm.xml file in src }
folder.(mapping file)
Create the class that retrieves Student is a POJO class containing two member variables, rollNo and name.
or stores the persistent object
and save it in src folder
It uses setter methods to set the values for member variables and getter methods
to fetch the values.
Run the application
Setting Up a Project with Hibernate: Step 4
Create a Java project and add
required jars from the required
folder of hibernate downloads Hibernate configuration file configures class Student to table studentname using
<hibernate-mapping> tag. Hibernate.cfg.xml is used to mention database detail.
Add ojdbc14.jar or
mysqlconnector.jar depending
on the SQL vendor you are <?xml version='1.0' encoding='UTF-8'?>
connected to <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
Create the POJO class and save "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
it in src folder
<hibernate-configuration>
Create the hibernate.cfg.xml
<session-factory>
file in src folder (configuration
<property name="dialect">org.hibernate.dialect.MySQLDialect
file)
</property>
Create the <property name="connection.url">jdbc:mysql://localhost:3306/databasename</pro
ClassName.hbm.xml file in src perty>
folder (mapping file) <property name="connection.username">username</property>
<property name="connection.password">password</property>
Create the class that retrieves <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
or stores the persistent object <property name="hbm2ddl.auto">create</property>
and save it in src folder <mapping resource=“Student.hbm.xml"/>
</session-factory>
Add ojdbc14.jar or
Creating configuration object and hibernate.cfg.xml file:
mysqlconnector.jar depending
on the SQL vendor you are public class Client
connected to
{
StandardServiceRegistry standardRegistry = new
Create the POJO class and save .
it in src folder
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build
();
Create the hibernate.cfg.xml
file in src folder (configuration
file) Metadata metaData = new
MetadataSources(standardRegistry).getMetadataBuilder().build();
Create the sessionFactory = metaData.getSessionFactoryBuilder().build();
ClassName.hbm.xml file in src
folder (mapping file) }
Create the class that retrieves
or stores the persistent object
and save it in src folder
You have Learned how Hibernate uses XML mapping file for the transformation of data from POJO to
database tables and vice versa
Hibernate annotation is the newest way to define mappings without the use of XML file. You can use
annotations in addition to or as a replacement of XML mapping metadata.
Creating POJO Class With Annotation
@Entity // Every persistent POJO class is an entity and is declared using the @Entity
annotation (at the class level):
@Table // @Table annotation, hibernate will use the class name as the table name by default
private String name; // @Column annotation specifies the details of the column for this
property or field.
If // if it is is not specified, property name will be used as the column name by default.
Use POJO class student, hibernate.cfg.xml file, and annotations instead of hibernate mapping file.
Creating POJO Class With Annotation
RUNNING THE APPLICATION
}
}
Advanced Java
Topic 6—Hibernate CRUD Operation
CRUD Operation
The acronym CRUD stands for Create, Read, Update, and Delete
They are four basic operations that any data-driven application performs often
CREATE
READ
Application
UPDATE
DELETE
NATIVE SQL
Criteria
NATIVE SQL • Criteria API supports compile time checking for the query that we build, unlike HQL
Hibernate CRUD Operation
CREATE
Create and insert: The student table is created with two columns, rollNo and name. Let’s add data
for one student through the following code:
public class Client
{
CREATE public static void main(String [] args)
{
READ Configuration configuration= new Configuration().configure();
StandardServiceRegistry standardRegistry = new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
UPDATE Metadata metaData = new
MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
DELETE Session s = factory.openSession();
Transaction t=s.beginTransaction();
Student s1=new Student ();
s1.setRollNo(1);
s1.setName(“yachaan”);
s.save(s1);
t.commit();
s.close();
} POJO class and hibernate.cfg.xml file remains same
}
Hibernate CRUD Operation
READ
To read and retrieve data, create a Student object with existing ID and sessionobject.get (Class clazz, Serializable id).
Create a Student object with existing ID and use sessionobject.update (Object object)
Create a Student object with existing ID and use sessionobject.delete (Object object)
Hibernate annotations is the newest way to define mappings without the use of
XML file. You can use annotations in addition to or as a replacement of XML
mapping metadata.
a. hibernate.xml
b. hibernate.config.xml
c. hibernate.properties
d. hibernate.cfg.xml
QUIZ
Which of the following is the hibernate configuration file?
1
a. hibernate.xml
b. hibernate.config.xml
c. hibernate.properties
d. hibernate.cfg.xml