Lesson 6 - Hibernate Queries and Relationship
Lesson 6 - Hibernate Queries and Relationship
Discuss HQL
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 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 SQL Query: Select * from Student, where Student
class name is one table name
Features of HQL
• HQL is object-oriented
• UPDATE
• DELETE
• SELECT
Using HQL, we can move table data to another table. However, we cannot insert
data using HQL.
Creating HQL Query
3. Open Session
Session sn = sf.openSession();
4. Create query
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.
setString: This informs Hibernate that the parameter date type is String
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
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
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.
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.
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
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();
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:
Let’s assume we have one table named student, and one class named Student mapped to student
table, which has following structure:
class Student
{
private int rollno;
private String name;
private int age;
private int marks;
//getter and setter methods
}
Applying Criteria Query
Session s; s.createCriteria(Student.class).list();
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
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?
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
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
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:
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
Columns declared by the subclasses may not have NOT NULL constraints.
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
{
...
}
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.
Component
Mapping Employee Owner
person_id:Integer person_id:Integer
joining_date: Date stocks: Integer
department name: Char department name: Char
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,
}
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
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;
} }
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.
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
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 }
} }
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);
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
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
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
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
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.
Transaction succeeded
commit
rollback
Transaction failed
Transaction Interface
In hibernate framework, we have transaction interface that defines the unit of work.
• void commit() ends the unit of work unless you are in FlushMode.NEVER.
• void setTimeout(int seconds) sets a transaction timeout for any transaction started by a subsequent call to
begin on this instance.
Hibernate provides its own language known as Hibernate Query Language. The
syntax is quite similar to database SQL language.
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