0% found this document useful (0 votes)
54 views70 pages

Lesson 6 - Hibernate Queries and Relationship

The document discusses Hibernate queries including Hibernate Query Language (HQL), native SQL queries, and criteria queries. It explains how to use HQL for CRUD operations and describes HQL syntax elements like the from, where, and select clauses.

Uploaded by

Naveen Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views70 pages

Lesson 6 - Hibernate Queries and Relationship

The document discusses Hibernate queries including Hibernate Query Language (HQL), native SQL queries, and criteria queries. It explains how to use HQL for CRUD operations and describes HQL syntax elements like the from, where, and select clauses.

Uploaded by

Naveen Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Advanced Java

Lesson 6—Hibernate Queries and Relationships

© Simplilearn. All rights reserved.


Learning Objectives

Discuss HQL

Describe Native SQL Query and Criteria Query

Explain caching in Hibernate

Explain Transaction management


Advanced Java
Topic 1—Hibernate Query Language (HQL)
Why HQL: Example
Analyze the following code to retrieving student record from student table:

public class Test


{
org.hibernate.cfg.Configuration cfg= new
org.hibernate.cfg.Configuration().config
// POJO class
ure("onetomany/hibernate.cfg.xml");

class Student
StandardServiceRegistryBuilder id name
{
hibernate.cfg.xml builder= new
private int id;
StandardServiceRegistryBuilder().applySe
private String name;
ttings(cfg.getProperties());
// getter and setter 1 John
SessionFactory
methods
factory=cfg.buildSessionFactory(builder.
}
build());
Session s=
factory.openSession();
s.beginTransaction();
Person user=new Person();
Student s1=user.get(Person.class,1);

}
Student table
Why HQL?

To retrieve the student’s data, we provide primary key value for that Student: user.get(Person.class,1);

If one table doesn’t have a primary key, the records cannot be retrieved.

Hibernate provides its own language known as Hibernate Query Language, to solve such problems.
The syntax is quite similar to database SQL language,
What Is HQL?

HQL is used to communicate with a database.


It is a Hibernate language for relational database management systems. HQL statements are used
to perform tasks such as updating data on a database or retrieving data from a database.

HQL Queries

Hibernate

Retrieve data
HQL vs. SQL

HQL SQL
It is related to hibernate framework It is related to a specific database
HQL queries are object queries SQL queries are table queries
Example: Example: Student table

class Student
{ Id name
String name;
int id;
}

HQL Query :- from Student


where Student is one class name

HQL Query: from Student, where Student is one SQL Query: Select * from Student, where Student
class name is one table name
Features of HQL

• HQL is object-oriented

• It understands notions like inheritance, polymorphism, and association

• Its queries are case-insensitive, unlike queries in Java classes.

Example: For HQL queries, SeLeCT is the same as sELEct


but for Java class org.hibernate.eg.STUDENT is not equal to org.hibernate.eg.Student.
Uses of HQL

Using HQL, we can create required CRUD operations:

• UPDATE
• DELETE
• SELECT

Using HQL, we can move table data to another table. However, we cannot insert
data using HQL.
Creating HQL Query

1. Create configuration object and hibernate.cfg.xml file

StandardServiceRegistry standardRegistry = new


StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

2. Create SessionFactory object

Metadata metaData = new


MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory sf =
metaData.getSessionFactoryBuilder().build();

3. Open Session

Session sn = sf.openSession();

4. Create query

Query query = sn.createQuery(“Here you can write HQL Query”);


Methods of Query Interface

1. getReturnType() - Return the Hibernate types of the query result set

1. iterate() - Return the query results as an Iterator

1. list() - Return the query results as a List


Hibernate Parameter Building

Named parameters: This is the most common way method followed by a parameter name (:example) to
define a named parameter. Suppose we have Stock table with stockCode column.

setParameter: The setParameter discovers the parameter data type

String hql = "from Stock s where s.stockCode = :stockCode";


List result = session.createQuery(hql) .setParameter("stockCode",
“1111") .list();

setString: This informs Hibernate that the parameter date type is String

String hql = "from Stock s where s.stockCode = :stockCode";


List result = session.createQuery(hql) .setString("stockCode", “1111") .list();

setProperties: This can be used to pass an object to the parameter binding. Hibernate will automatically
check the object’s properties and match them with the colon parameter

Stock stock = new Stock(); stock.setStockCode(“1111");


String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql) .setProperties(stock) .list();
HQL Syntax

1. from clause
2. Aliasing
3. Aggregate functions and select clause
4. where clause
5. Expressions
6. order by clause
7. Associations and Joins
HQL Syntax
from clause

from clause
from packagename.class_name returns all instances of the class.

Aliasing Suppose there is a Student table with rollNo and name member variable corresponding to Student
class.
Aggregate
functions and To fetch the data from Student table, use the following syntax:
select clause
String hql = "FROM Student";
where clause Query query = session.createQuery(hql);
List results = query.list();

Expressions

order by
clause

Associations
and Joins
HQL Syntax
Aliasing

from clause
You can assign an alias that is a different name to the class. Suppose alias name is als. The syntax
can be:
Aliasing
from ClassName as als
Aggregate
functions and
select clause
This query assigns the alias als to ClassName instances, so that you can use that alias later.

where clause

Expressions

order by
clause

Associations
and Joins
HQL Syntax
Aggregate functions and select clause

from clause
To get results of aggregate functions on the properties select avg(std.marks), sum(std.marks),
max(cat.marks), and count(std)from Student std, the supported aggregate functions are:
Aliasing
• avg(...), sum(...), min(...), max(...)
Aggregate
functions and • count(*)
select clause
• count(...), count(distinct ...), count(all...)
where clause
You can use arithmetic operators and concatenation

Expressions

order by
clause

Associations
and Joins
HQL Syntax
where clause

from clause
The where clause allows you to refine the list of instances.

Aliasing • from ClassName where column_name='Ram‘: If there is an alias, use a qualified property name

Aggregate • from ClassName as als where als.column_name='Ram‘: This returns instances of ClassName
functions and named 'Ram'
select clause

where clause

Expressions

order by
clause

Associations
and Joins
HQL Syntax
Expressions

from clause Expressions include:


• mathematical operators: +, -, *, /
Aliasing • binary comparison operators: =, >=, <=, <>, !=, like
• logical operations: and, or, not
Aggregate • Parentheses ( ) that indicate grouping
functions and
select clause • in, not in, between, is null, is not null, is empty, is not empty, member of, and not member of
• "Simple" case, case ... when ... then ... else ... end, and "searched" case, case when ... then ... else ... end
where clause • string concatenation ...||... or concat(...,...)
• current_date(), current_time(), and current_timestamp()
Expressions • second(...), minute(...), hour(...), day(...), month(...), and year(...)
• Any function or operator defined by EJB-QL 3.0: substring(), trim(), lower(), upper(), length(), locate(),
order by
abs(), sqrt(), bit_length(), mod()
clause • coalesce() and nullif()
• str() for converting numeric or temporal values to a readable string
Associations
and Joins
HQL Syntax
order by clause

from clause
This clause uses a ordered list by any property that is either ascending (ASC) or descending (DESC).

Example:
Aliasing
Suppose there is a list of employees and you need to find their salaries in decreasing order. The
Aggregate
functions and following syntax can be used:
select clause
"FROM Employee E ORDER BY E.salary DESC";
where clause

Expressions

order by
clause

Associations
and Joins
HQL Syntax
Associations and Joins

from clause
Join is used to associated entities or elements of a collection of values.

Aliasing The join types are as follow:

Aggregate • inner join


functions and
select clause • left outer join
• right outer join
where clause
• full join

Expressions The inner join, left outer join ,and right outer join constructs may be abbreviated.
You may supply extra join conditions using the HQL with keyword
order by
clause

Associations
and Joins
Advanced Java
DEMO—Programs on HQL
Advanced Java
Topic 2—Native SQL Queries
Native SQL Queries

1. createSQLQuery() method is used to create native SQL Query for the session.
2. You can create SQL, including stored procedure, for all create, update, delete operations using Hibernate 3.x.
3. The result can be added to Hibernate entity.

How to write SQL Query :


Session s;
SQLQuery query = s.createSQLQuery(“ Here you can write native SQL Queries“
);

Hibernate provides an option to execute native SQL queries through the use of SQLQuery object.
Native SQL: Example
Consider a table that has the following data:
Person

PERSONID FIRSTNAME LASTNAME


-------- ---------- ---- -----------
1 Marry SMITH
1 Carl SMITH
2 JOHN SMITH

Name the database as record. POJO class for creating above table:

Class Person
{
private int id;
private String firstNmae;
private String lastName;
// public getter and setter methods
}

Lets create a list of all persons record using Native SQL Query.
Native SQL: Example
/* Code to READ all the Person record using Entity Query */

Session session; // Let assume We have already created Session object by previous discussed steps.
Transaction tx = null;
try{
tx = session.beginTransaction();
String sql = "SELECT * FROM PERSON";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Person.class);
List person = query.list();

for (Iterator iterator = person.iterator(); iterator.hasNext();)


{
Person person = (Person) iterator.next();
System.out.print("First Name: " + person.getFirstName());
System.out.print(" Last Name: " + person.getLastName());
}
tx.commit();
}
catch (HibernateException e)
{
if (tx!=null) tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
Advanced Java
Topic 3—Criteria Queries
What Is Criteria Query?

Criteria Query allows you to apply filtration rule and logical condition with query.

org.hibernate.Criteria Query is a method provided by Criteria API that helps in creating criteria query
programmatically.
Restriction Class

The criterion package may be used by applications as a framework for building new kinds of criteria.

However, it is intended that most applications will simply use the built-in criterion types via the static factory
methods of Restrictions class:

Restriction class Description


static SimpleExpression eq(String
Applies an "equal" constraint to the named property
propertyName, Object value)
static SimpleExpression gt(String
Applies a "greater than" constraint to the named property
propertyName, Object value)
static PropertyExpression
neProperty(String propertyName, String Applies a "not equal" constraint to two
otherPropertyName)
static SimpleExpression like(String
Applies a "like" constraint to the named property
propertyName, Object value)
static Criterion between(String
Applies a "between" constraint to the named property
propertyName, Object lo, Object hi)
Criteria Query: Example

Let’s assume we have one table named student, and one class named Student mapped to student
table, which has following structure:

Roll no Name Age Marks

Structure for Student class:

class Student
{
private int rollno;
private String name;
private int age;
private int marks;
//getter and setter methods
}
Applying Criteria Query

Criteria Query in given table can be applied in two ways:

1. Criteria Query without restrictions

Session s; s.createCriteria(Student.class).list();

This will show data of student table in the form of a list.

2. Criteria Query with restrictions

Session s;
Criteria crt = s.createCtriteria(Student.class);
crt.add(Restrictions.gt(“age”,23));
List <Student> list = crt.list();

This will show data of student table in form of a list with age greater than 23.
Advanced Java
Topic 4—Catching in Hibernate
Cache and Caching

• Cache is a component that stores data temporarily so future requests for that data can be served faster
• Cache is a temporary storage area
• Caching is a process to store data in cache
• Caching in Hibernate avoids database hits and increases performance of critical applications
Cache Hierarchy in Hibernate

Hibernate follows multilevel cache schema, as shown:

Hibernate

Java Application First Level Session Second Level


Cache Object Cache
Types of Cache in Hibernate

First - Level Cache:

1. All caches must pass through First-Level Cache.


2. When you close the Session object, all objects being cached are lost and persist or are updated in database.

Second - Level Cache:

1. It is an optional cache
2. It uses a common cache for all the session objects of a session factory.

Example:

JBoss cache as a Hibernate Second - Level Cache. It is tree-structured, clustered, transactional cache.
Advanced Java
Topic 4—Mapping Relationship with Hibernate
Why Mapping?

Hibernate mapping is used for the following:

• To map inheritance hierarchy classes with the table of the database


• To meet the need of mapping collection elements of Persistent class in Hibernate
• To map dependent object as a component
• Hibernate mapping is used to map Java data type to SQL data type and vice versa. Hibernate
uses Hibernate Type, which is different from Java data type and SQL data type
Hibernate Types

1. Value type has the following types:

• Basic value Type: Hibernate provides a number of built-in basic types


• Composite type: Components represent aggregation of value into a single Java type
• Collection type: To map collection, Hibernate provides collection type

2. Entity type: Entities are classes that correlate with row in table

3. Custom type: Hibernate allows you to create your own value types
Types of Mapping in Hibernate

1. Inheritance Mapping
2. Association Mapping
3. Collection Mapping
4. Component Mapping
Types of Mapping in Hibernate
INHERITANCE MAPPING

Java inheritance relationship between classes is represented as follows:

Inheritance
Mapping class ParentClass
{
Association
Mapping
}
Collection
Mapping extends
Component
Mapping
class ChildClass extends ParentClass
{

We can map the inheritance hierarchy classes with the table of the database using inheritance mapping.
Types of Mapping in Hibernate
INHERITANCE MAPPING: TYPES

There are three types of inheritance mapping:


Inheritance
Mapping
• Single Table per Class Hierarchy Strategy: the <subclass> element in Hibernate
Association
Mapping • Table per class: the <union-class> element in Hibernate

Collection • Joined Subclass Strategy: the <joined-subclass> element in Hibernate


Mapping
Component
Mapping
Types of Mapping in Hibernate
INHERITANCE MAPPING: SINGLE TABLE PER CLASS HIERARCHY STRATEGY

It is also known as Table per class. It uses one table. To distinguish classes, it uses discriminator
column. Lets take an example. Consider two classes as shown:

Inheritance Person class


Mapping @Entity
Association @Inheritance Employee class
@DiscriminatorColumn(
Mapping name="discriminator", @Entity
discriminatorType=DiscriminatorType.STRING) @DiscriminatorValue("E")
Collection @DiscriminatorValue(“P") public class Employee extends Person {
Mapping public class Person private String departmentName;
{ private Date joiningDate;
Component @Id //setter and getter methods
Mapping private int personId;
private String fName; }
private String lName;
// setter and getter method;
}

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: SINGLE TABLE PER CLASS HIERARCHY STRATEGY

Let’s create object for Employee class


Person person = new Person();
person.setFirstname(“john");
Inheritance person.setLastname(“sully");
Mapping person.setPersonId(1);

Association
Mapping Employee employee = new Employee(“linda", “watson", "Tech", new Date());
s.save(person);
Collection s.save(employee);
Mapping
Component discriminator id fName lName departmentName joiningDtae
Mapping
P 101 John Sully null null

E 102 Linda Watson tech 2017-08-08 17:53:58

Columns declared by the subclasses may not have NOT NULL constraints.

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: TABLE PER CLASS

Table Per class contains three tables in the database that are not related to each other. There
are two ways to map the table with table per concrete class strategy.
Inheritance
• By union-subclass element
Mapping
Association • By Self creating the table for each class
Mapping
Syntax:
Collection
Mapping
@Entity
Component @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
Mapping public class Flight implements Serializable
{
...
}

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: PROPERTIES OF TABLE PER CLASS

1. Each sub-table has a column for all properties, including inherited properties.
Inheritance
Mapping 2. Column name is the same in all sub tables.

Association 3. Primary key seed is shared in all sub tables.


Mapping
Collection
Mapping
Component
Mapping

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

• It is also known as One Table Per Subclass


Inheritance
• It uses n number of tables, where n = total number of classes, including sub and super
Mapping
classes
Association
Mapping • It uses one-to-one association
Collection • All subtables use primary key association with super table
Mapping
• The @PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns annotations define the primary
Component key(s) of the joined subclass table
Mapping

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

The @PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns annotations define the primary


key(s) of the joined subclass table:
Inheritance
Mapping
Association Person
Mapping person_id:Integer
Collection firstname: Char
Mapping lastname: Char

Component
Mapping Employee Owner
person_id:Integer person_id:Integer
joining_date: Date stocks: Integer
department name: Char department name: Char

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

Person class Employee class


@Entity
@Entity
@Table(name = "PERSON")
@Table(name="EMPLOYEE")
Inheritance @Inheritance(strategy=InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name="PERSON_ID")
public class Person {
Mapping public class Employee extends Person {
@Id
@Column(name="joining_date")
Association @GeneratedValue
private Date joiningDate;
@Column(name = "PERSON_ID")
Mapping private Long personId;
@Column(name="department_name")
private String departmentName;
@Column(name = "FIRSTNAME")
Collection public Employee() {
private String firstname;
Mapping @Column(name = "LASTNAME")
}
public Employee(String firstname,
private String lastname;
Component public Person() {
String lastname, String departmentName, Date
Mapping }
joiningDate) {
super(firstname, lastname);
public Person(String firstname, String
this.departmentName =
lastname) {
departmentName;
this.firstname = firstname;
this.joiningDate = joiningDate;
this.lastname = lastname;
}
}
// Getter and Setter methods,
// Getter and Setter methods,
}
}

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

Owner class
@Entity
Inheritance @Table(name="OWNER")
@PrimaryKeyJoinColumn(name="PERSON_ID")
Mapping
public class Owner extends Person {
Association @Column(name="stocks")
Mapping private Long stocks;
@Column(name="partnership_stake")
Collection private Long partnershipStake;
Mapping public Owner() {
}
Component public Owner(String firstname, String lastname, Long stocks, Long
Mapping partnershipStake) {
super(firstname, lastname);
this.stocks = stocks;
this.partnershipStake = partnershipStake;
}
// Getter and Setter methods,
}

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

Database representation:
Person table
Inheritance
Mapping person_id firstname lastname
1 Steve Balmer
Association
Mapping 2 James Gosling
3 Bill Gates
Collection
Mapping
Employee table Owner table
Component
Mapping person_id joining_date department_name person_id stocks partnership_stake
2 2011-12-23 Marketing 3 300 20

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
ASSOCIATION MAPPING

It is a mapping relationship between two objects in Java

Inheritance class classdiagram


Mapping
Association
Mapping Car Customer
Collection
owner • address: String
Mapping • modelNumber: String
Component • contactNumber: String
• owner: Customer
Mapping • name: String
Types of Mapping in Hibernate
ASSOCIATION MAPPING: TYPES

Inheritance 1. One to One


Mapping 2. One to Many
Association 3. Many to One
Mapping
4. Many to Many
Collection
Mapping
Component
Mapping
Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO ONE

A one-to-one relationship occurs when one entity is related to exactly one occurrence in
another entity.

Inheritance Example:
Mapping
Association Person Passport
Mapping
Collection
Mapping One person is associated with one passport, and one passport belongs to one person. Here,
Person class and Passport class have one-to-one relationship.
Component
Mapping
class Person{ class Passport
private int id; {
private String name;
private int id;
private Date valid_date;
} }

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO ONE

The annotation used to generate one to one mapping between person and passport table is
@OneToOne .
Inheritance Person class Passport class
Mapping
@Entity @Entity
Association @Table (name=”PERSON”) @Table (name=”PASSPORT”)
Mapping class Person{ class Passport
@Id {
Collection private int id; @Id
Mapping private String name; private int id;
@OneToOne private Date valid_date;
Component private Passport passport; }
Mapping }

Hibernate creates one column in Person table corresponds to PASSPORT table id column.

When member variable is sent to Person, set Passport member of Person class can be
avoided.

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO ONE

Let’s create the object of Person class and Passport class:

Inheritance Person p=new Person(); Person Table


Mapping p.setId(1); id name passport_id
p.setName(“John”);
Association Passsport k=new Passport(); 1 John 101
Mapping k.setId(101);
k.setValue(“abc); Passport Table
Collection p.setPassport(k);
Mapping session.save(p); id value
Component session.save(k);
101 abc
Mapping

If foreign key is added, annotation used should be @JoinColumn(name="passport_fk").

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO MANY

Consider a scenario where one Employee has multiple phone numbers and one phone number
Inheritance belongs to one Employee.
Mapping
Association Phone
Mapping Employee One to many
mapping Phone
Collection • address Address
Phone
Mapping • id integer
• name String • areaCode String
Component • phones Vector • id integer
Mapping
One to one mapping • owner Employee
Java Class (source) • number String

Java Classes (target)

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO MANY

Creating classes:
Employee Class:
Inheritance class Person Phone Class:
@Entity
Mapping { @Table(name="EMPLOYEE") @Entity
int id; public class Employee { @Table(name="Phone")
Association public class Phone {
String name; @Id
Mapping private int @Id
} private int
Collection employeeId;
@OneToMany PhoneId;
Mapping class Phone
private int
private collection
{ PhoneNumber;
Component <Phone>=new ArrayList <
int id; //setter and getter methods
Mapping phone>();
int phoneNumber; // setter getter methods }
} }

Add user defined name using the following annotation:


@JoinTable(name=”USER_VEHICLE”, join Column=@Join Column(name=”USER_ID”)
inverseJoinColumns=@JoinColumn(name=”VEHICLE_ID”)

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO MANY

Creating objects for Person and Phone classes:

Person table
Inheritance Person user=new Person();
Mapping
user.setId(1); id name
user.setName(“john”); 1 john Person_Phone table
Association Phone p1= new Phone();
p1.(101); 2 Stella
Mapping person_id phone_id
p1.(123456789);
Phone table 1 101
Collection user.getPhone().add(p1);
Mapping Phone p2= new Phone(); id phoneNumber 1 102
p2.(102);
Component p2.(1112131415); 101 123456789
Mapping user.getPhone().add(p2); 102 1112131415
session.save(user);
session.save(p1);session.save(p2);

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: MANY TO ONE

Let’s consider the same scenario again. Many phone numbers can belong to one person.

Inheritance
Mapping
Employee Phone
Association One to many
mapping Phone
Mapping
• address Address
Phone
Collection • id integer
Mapping • name String • areaCode String
• phones Vector • id integer
Component
• owner Employee
Mapping Java Class (source)
One to one mapping
• number String

Java Classes (target)

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: MANY TO ONE

Creating classes: Person Class: Phone Class

Inheritance class Person @Entity


Mapping { @Table(name="Phone")
@Entity
int id; public class Phone {
@Table(name="PERSON")
Association String name; public class Person {
@Id
Mapping } @Id
private int Id;
private int
Collection private int id;
class Phone phoneNumber;
private String name;
Mapping { @ManytoOne
// setter getter methods
int id; private Person person
Component int phoneNumber;
}
//setter and getter methods
Mapping } }

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: MANY TO ONE

Creating objects for Person and Phone class

Inheritance Person user=new Person(); Person table


Mapping user.setId(1);
id name
user.setName(“john”);
Association Phone p1= new Phone(); 1 john
Mapping p1.(101); 2 Stella
p1.(123456789);
Collection p1.setPerson(user); Phone table
Mapping Phone p2= new Phone();
p2.(102); id phoneNumber
Component p2.(1112131415); 101 123456789
Mapping p2.setPerson(user);
102 1112131415
session.save(user);
session.save(p1);session.save(p2);

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: MANY TO MANY

A many-to-many association is defined logically using the @ManyToMany annotation. You also
have to describe the association table and the join conditions using the @JoinTable annotation.
Inheritance
Mapping
Association Employee Meeting
Mapping 1 1
Collection employee_id meeting_id
Mapping
firstname subject
Component Employee_Meeting
lastname meeting_date
Mapping
employee_id

meeting_id

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
COLLECTION MAPPING

Hibernate allows you to map collection elements of Persistent class. It can be done by
Inheritance declaring the type of collection in Persistent class from one of the following types:
Mapping
Association • java.util.List
Mapping
• java.util.Set
Collection
• java.util.SortedSet
Mapping
• java.util.Map
Component
Mapping • java.util.SortedMap
• java.util.Collection
• or write the implementation of org.hibernate.usertype.UserCollectionType
Types of Mapping in Hibernate
COMPONENT MAPPING

Component refers to the object-oriented notation.

Inheritance For example: Student class has one class member: Name. Name is also one class that has two
Mapping members, firstName and lastName.

Association
Phone Class
Mapping Person Class
@Entity
Collection @Entity
@Table(name="Phone")
Mapping @Table(name="PERSON")
public class Phone {
public class Person {
@Id
Component @Id
private int Id;
Mapping private int id;
private int
private String name;
phoneNumber;
@ManytoMany
@ManytoOne
private Collection<Meeting>=new
private Collection <Person > person=new
ArrayList();
ArrayList();
// setter getter methods
//setter and getter methods
}
}
Types of Mapping in Hibernate
COMPONENT MAPPING

Creating objects for Person and Phone class:

Person user=new Person();


Person table Phone table
Inheritance user.setId(1);
Mapping user.setName(“john”); id name id phoneNumber person_id
Meeting p1= new Meeting();
Association p1.(101); 1 john 101 123456789 1
Mapping p1.(123456789); 2 Stella 102 1112131415 1
p1.getPerson().add(user);
Collection Phone p2= new Phone();
Mapping meeting_person TABLE person_meeting TABLE
p2.(102);
p2.(1112131415);
Component meeting_id person_id id phoneNumber
p2.getPerson().add(user);
Mapping user.getMeeting().add(p1); 101 1 1 101
user.getMeeting().add(p2);
session.save(user); 102 1 1 102
session.save(p1);session.save(p2);

In component mapping, the dependent object is mapped as a component. A component is an object that is
stored as a value rather than entity reference. This is mainly used if the dependent object doesn't have
primary key. It is used in case of composition (HAS-A relation). That is why it is termed component.
Advanced Java
Topic 5—Transaction Management
What Is Transaction Management?

A transaction simply represents a unit of work if one step fails, the whole transaction fails.

It is described by ACID properties (Atomicity, Consistency, Isolation, and Durability).

Transaction succeeded
commit

Initial state Transaction

rollback
Transaction failed
Transaction Interface

In hibernate framework, we have transaction interface that defines the unit of work.

• A transaction is associated with Session and instantiated by calling session.beginTransaction().

• void begin() starts a new transaction

• void commit() ends the unit of work unless you are in FlushMode.NEVER.

• void rollback() forces this transaction to rollback.

• void setTimeout(int seconds) sets a transaction timeout for any transaction started by a subsequent call to
begin on this instance.

• boolean isAlive() checks if the transaction is still alive.

• void registerSynchronization(Synchronizations) registers a user synchronization callback for this transaction.

• boolean wasCommited() checks if the transaction was committed successfully.

• boolean wasRolledBack() checks if the transaction was rolled back successfully.


Key Takeaways

Hibernate provides its own language known as Hibernate Query Language. The
syntax is quite similar to database SQL language.

HQL is a Hibernate language for relational database management


systems. HQL statements are used to perform tasks such as updating data on a
database or retrieving data from a database.

The criterion package may be used by applications as a framework for building


new kinds of criterion.

Hibernate provides the option to execute native SQL queries through the use
of SQLQuery object.

Criteria Query allows you to apply filtration rule and logical condition with query.
org.hibernate.Criteria Query is a method provided by Criteria API that helps in
creating criteria query programmatically.
Quiz
Thank You

You might also like