Professional Documents
Culture Documents
Unit 2: or Mapping - Relations and Inheritance: Confidential Er/Corp/Crs/ /003
Unit 2: or Mapping - Relations and Inheritance: Confidential Er/Corp/Crs/ /003
Confidential
Mapping relationships
Types one-to-one Either end can be the owner (only one) many-to-one Many end must be the owner one-to-many Many end must be the owner many-to-many Either end can be owner
Confidential
Confidential
One-To-One Unidirectional
package org.demo; class Person { private int personId; .. private Email address; ... } package org.demo; class Email { private int pk_id; ... }
Infosys Technologies Ltd.
Confidential
Confidential
Email
PK Id email
PK,FK userId
PK,FK emailId
Confidential
One-To-Many Relationship
<set> <bag> <list> <array>
Confidential
Confidential
Confidential
public class EventManyToMany { private Long id; private String name; private int duration; private Set speakers; public void setSpeakers(Set speakers) { Infosys Technologies Ltd. this.speakers = speakers; } public Set getSpeakers() { return speakers; } We enable you to leverage knowledge 19 Confidential 2008, Infosys Technologies Ltd. anytime, anywhere! // ...
Many to Many relationship One Event has many speakers and one speakers participates in many events <class name="SpeakerManyToMany table="m_speakers"> <id name="id" column="uid" type="long"> <generator class="increment"/> </id> <property name="firstName" type="string" length="20"/> <property name="lastName" type="string" length="20"/> Infosys Technologies Ltd. <set name="events" table="event_speakers cascade="all"> <key column="speakers_id"/> <many-to-many class="EventManyToMany"/> </set></class>
21 2008, Infosys Technologies Ltd. Confidential We enable you to leverage knowledge anytime, anywhere!
Inheritance
Three strategies One table per class One table per subclass One table per concrete class
Confidential
Example
class Payment payment_id amount class CreditCardPayment creditcard_type
Confidential
24
Confidential
27
Confidential
30
Confidential
32
Confidential
Criteria Query API Queries can be constructed using a set of Java Objects instead of query language Lets you assemble nested, structured query expressions in Java programming language Compile time syntax checking possible Polymorphic behavior is supported Eg:get instances of X & subclass(X) Supports Query By Example (QBE) Querying by providingInfosys Technologies Ltd. object which an example contain properties that has to be retrieved Supports aggregation methods (from Hibernate 3 onwards)
Confidential
Confidential
Confidential
40
Confidential
Confidential
42
Aggregate Functions
avg(String propertyName) average of a property's value count(String propertyName) number of times the given property has a value countDistinct(String propertyName) number of unique values the said property contains max(String propertyName) min(String propertyName) Infosys Technologies Ltd. sum(String propertyName) sum of the property values
Confidential
Aggregate Functions
[contd]
We can call different aggregate functions using the Projections factory class. Once the projection object is created add it to the criteria object using setProjection() method Eg:-The result will contain one object, an Integer that Holds the results of executing Avg(Salary)SQL statement Infosys Technologies Ltd. Criteria crit = sess.createCriteria(Employee.class); crit.setProjection( Projections. avg (salary) ); List results = crit.list();
Confidential
Confidential
Confidential
Confidential
from clause
Return all instances of the class example.Event from example.Event
Usually don't need give the fully qualified name of the class , since auto-import is the default.
from Event = from example.Event
you can assign an alias, so that you can refer to the class in other parts of the query Technologies Ltd. Infosys
from Event as evt (evt is the alias) from Event evt (as can be omitted)
Confidential
Alias
Multiple classes may emerge, resulting in a Cartesian product or "cross" join. from Employee, Dependants from Formula as emp, Dependants as deps Tip : query aliases can be named using an initial lowercase so that it is consistent with Java naming standards for local variables
Infosys Technologies Ltd.
Confidential
Join
We may also assign aliases to elements of a collection of values or to associated entities, using a join Eg1. from Event as evt inner join evt.speakers as spk left outer join sp.venue as venue Eg:2 from Event as evt left join evt.speakers.venue as venue
Infosys Technologies Ltd.
Confidential
Confidential
select clause
The select clause picks which properties & objects to return in the query result set select spk from Event as evt inner join evt.speaker as spk Compact form select evt.speaker from Event evt
Infosys Technologies Ltd.
Confidential
select clause
properties of any value type including the properties of component type can be returned by Queries select evt.name from Event evt where evt.name like Hib%' select cust.name.firstName from Customer as cust properties as an array of type Object[ ] and/or multiple Infosys Technologies Ltd. objects can be returned by Queries
select mother, offspr, mate.name from DomesticCat as mother inner join mother.mate as mate left outer join mother.kittens as offspr
56 2008, Infosys Technologies Ltd. Confidential We enable you to leverage knowledge anytime, anywhere!
where clause
The list of instances returned can be narrowed by the Where clause. you may refer to properties by name ,If no alias exists from Event where name=Hibernate Session' use a qualified property name ,If there is an alias : from Event as evt where evt.name= Hibernate Session'
Infosys Technologies Ltd.
Confidential
where clause
[cont]
Return all instances of Event for which there exists an instance of Speaker with a id property equal to the spkid property of the Event select evt from Event evt, Speaker spk where evt.spkid = spk.id Compound path expressions make the where clause Infosys Technologies Ltd. extremely powerful. from Event evt where evt.speaker.name is not null
Confidential
[contd]
System.out.println("\n---Using SQL query with where clause..."); String sql = "select * from Supplier supplier"; SQLQuery query = session.createSQLQuery(sql); query.addEntity("supplier", Supplier.class); List results = query.list(); displaySupplierList(results);
}
Infosys Technologies Ltd.
Demo Program
Table Name:EMPOLOYEE
ID
1001
name
John
salary joining_date
10000 12-jan-2009
1003
Angel
23000
14-jun-2008
1004
Joy
22000
23-apr-2007
Confidential
Program to find out the lowest salary amount from the table (Aggregate Function)
package demo; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
Confidential
Program to find out the lowest salary amount from the table (Aggregate Function) [contd]
String SQL_QUERY = "select min (salary) from Employee emp"; Query query = sess.createQuery(SQL_QUERY); List list = query.list();
System.out.println("Min Salary Amount: " + list.get(0));
Confidential
Program to find out the lowest salary amount from the table (Aggregate Function) [contd]
Output: Min Salary Amount: 10000
Confidential
Demo 2: Select HQL Example package demo;; import org.hibernate.Session; import org.hibernate.*; import org.hibernate.cfg.*; import java.util.*; public class SelectHQLExample { public static void main(String[] args) { Session session = null; try{ Infosys Technologies Ltd.
// prepare hibernate for use after reading the hibernate.cfg.xml
{ Employee emp=(Employee)it.next(); System.out.println("ID: " + emp.getId()); System.out.println("First Name: " + emp.getName()); Infosys Technologies Ltd. } session.close(); } catch(Exception e){ System.out.println(e.getMessage()); }finally{ }}}
2008, Infosys Technologies Ltd.
Confidential We enable you to leverage knowledge anytime, anywhere!
Confidential
Confidential
Summary
Introduction- Introduction to ORM & Hibernate Hibernate Architecture and Framework Hibernate Instance States ,Lifecycle Operation Hibernate Configurations Primary Key Generation, Composite Key, Hibernate Data Types OR Mapping-Relations and Inheritance Infosys Technologies Ltd. Criteria Query API, HQL & native SQL
Thank You
Infosys Technologies Ltd.
Confidential