+ All Categories
Home > Documents > Hibernate Day2

Hibernate Day2

Date post: 05-Apr-2018
Category:
Upload: ravi-kant-sharma
View: 242 times
Download: 1 times
Share this document with a friend

of 69

Transcript
  • 8/2/2019 Hibernate Day2

    1/69

    2008, InfosysTechnologies Ltd.

    Confidential

    Unit 2 : OR Mapping Relations andInheritance

    ER/CORP/CRS//003

  • 8/2/2019 Hibernate Day2

    2/69

    We enable you to leverage knowledge

    anytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Hibernate Mapping Files

    Object Relational mapping defined in XML document

    Mapping documents are readable and hand-editable

    Mapping language is java-centric, mapping constructedaround persistent classes not table declaration

    Can use tool like XDoclet and annotation

    Define identifier generation, properties, objectrelationship ..

    2

  • 8/2/2019 Hibernate Day2

    3/69

    We enable you to leverage knowledge

    anytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. 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

    3

  • 8/2/2019 Hibernate Day2

    4/69

    We enable you to leverage knowledge

    anytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One to One Relationship

    Expresses a relationship between two classes where

    each instance of the first class is mapped to a singleinstance of the second class or vice versa

    One to One relationship can be implemented in thedatabase in different two ways

    Giving each of the respective tables the same primarykey values

    Using foreign key constraint from one table onto aunique identifier column of the other

    4

    Email

    PK Id

    email

    FK- userId

    USER

    PK Id

    userName

  • 8/2/2019 Hibernate Day2

    5/69

    We enable you to leverage knowledge

    anytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. 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;

    ... }

    5

  • 8/2/2019 Hibernate Day2

    6/69

    We enable you to leverage knowledge

    anytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    The Mapping File

    ...

  • 8/2/2019 Hibernate Day2

    7/69

    We enable you to leverage knowledge

    anytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One-to-Many and Many-to-one AssociationRelationship Representation

    By foreign key, with no additional constraints

    Link table by maintaining foreign key into each ofassociated tables

    Unique constraint to be specified on the one side ofrelation (one to many) else it will be many to many

    7

    USER

    PK Id

    userName

    Email

    PK Id

    email

    USER_Email

    PK,FK userId

    PK,FK emailId

  • 8/2/2019 Hibernate Day2

    8/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One-To-Many Relationship

    9

  • 8/2/2019 Hibernate Day2

    9/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One to Many relationship: Creating ObjectInstance Country has many states

    public class Country {

    private Long countryid;

    private String name;

    // Country has one-to-many relationship with Statesprivate Set states;

    }

    public class State {

    private Long stateid;private String name;

    }

    10

  • 8/2/2019 Hibernate Day2

    10/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    1.One to Many :Using

  • 8/2/2019 Hibernate Day2

    11/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One to Many : Using Set in Domain Class

    Country has many states

    Country country=new Country();

    country.setName(India");

    country.setStates(new HashSet());country.getStates().add(new State(Maharashtra));

    country. getStates().add(new State(Gujarat));

    session.saveOrUpdate(country);

    12

  • 8/2/2019 Hibernate Day2

    12/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One to Many relationship :List

    public class Author{

    private int id;

    private String name;

    private List books;

    public void setBooks(List l) {bools = l;

    }

    public List getBooks() {

    return books;}

    // ...

    13

  • 8/2/2019 Hibernate Day2

    13/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    2. One to Many relationship:

    Author has written many books

    14

  • 8/2/2019 Hibernate Day2

    14/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One to Many relationship :

    public class Author{

    private int id;

    private String name;

    private Book[ ] books;

    public void setBooks(List l) {bools = l;

    }

    public List getBooks() {

    return books;}

    // ...

    15

  • 8/2/2019 Hibernate Day2

    15/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    3. One to Many relationship:

    16

  • 8/2/2019 Hibernate Day2

    16/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One to Many relationship :Object Instance

    ArrayList list = new ArrayList();

    list.add(new Book(Java"));

    list.add(new Book("Servlets"));

    list.add(new Book("JSP"));Author sp = new Author(Author1);

    sp.setBooks(list);

    17

  • 8/2/2019 Hibernate Day2

    17/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    4. One to Many relationship:

  • 8/2/2019 Hibernate Day2

    18/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Many to Many relationship:

    Event has many speakers

    public class EventManyToMany {

    private Long id;

    private String name;

    private int duration;private Set speakers;

    public void setSpeakers(Set speakers) {

    this.speakers = speakers;

    }

    public Set getSpeakers() {

    return speakers;

    }// ...

    19

  • 8/2/2019 Hibernate Day2

    19/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Many to Many relationship:

    A speaker speaks in many events

    public class SpeakerManyToMany {

    private Long id;

    private String first_Name;

    private String last_Name;private Set events;

    public Set getEvents() {

    return this.events;

    }

    public void setEvents(Set events) {

    this.events = events;

    }20

  • 8/2/2019 Hibernate Day2

    20/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Many to Many relationship

    One Event has many speakers and one speakersparticipates in many events

    21

  • 8/2/2019 Hibernate Day2

    21/69

    2008, InfosysTechnologies Ltd.

    Confidential

    Mapping Object Inheritance

    22

  • 8/2/2019 Hibernate Day2

    22/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Inheritance

    Three strategies

    One table per class

    One table per subclass

    One table per concrete class

    23

  • 8/2/2019 Hibernate Day2

    23/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Example

    class Payment

    payment_id

    amount

    class CreditCardPayment

    creditcard_type

    24

  • 8/2/2019 Hibernate Day2

    24/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One table per class hierarchy

    One table for the whole class hierarchy

    A discriminator column is a key to uniquely identify

    the base type

    Advantages

    This hierarchy offers the best performance even for inthe deep hierarchy since single select may suffice

    Disadvantages

    Changes to members of the hierarchy require column to

    be altered, added or removed from the table

    25

  • 8/2/2019 Hibernate Day2

    25/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One Table per Class Hierarchy

    How to define the mapping

    Use element and extend superclass usingextends

    define discriminator-value attributes

    26

  • 8/2/2019 Hibernate Day2

    26/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One table per Class Hierarchy

  • 8/2/2019 Hibernate Day2

    27/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One Table per Subclass

    One table for each subclass

    Foreign key relationship exists between common

    table and subclass tables

    Advantages

    Using this hierarchy, does not require complexchanges to the database schema when a singleparent class is modified

    It works well with shallow hierarchy

    Disadvantages As the hierarchy, it may result in poor performance

    The number of joins required to construct asubclass class also grows

    28

  • 8/2/2019 Hibernate Day2

    28/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One Table per Subclass

    Use element and extends attributes

    that defines the superclass

    29

  • 8/2/2019 Hibernate Day2

    29/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One Table per Subclass

  • 8/2/2019 Hibernate Day2

    30/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Mapping Inheritance:1 Table for ConcreteClass

    Map each of the concrete classes as a normal persistent

    class Advantages

    It is easiest to implement

    Disadvantages

    Data that belongs to a parent class is scatteredacross a number of subclass tables, whichrepresents concrete classes

    A query couched in terms of parent class is likely tocause a large number of select operations

    31

  • 8/2/2019 Hibernate Day2

    31/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Mapping Inheritance:One Table for ConcreteClass Changes to a parent class is reflected to large number of

    tables This hierarchy is not recommended for most cases

    32

  • 8/2/2019 Hibernate Day2

    32/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One Table per Concrete Class

    The mapping of the subclass repeats the properties of

    the parent class

    33

  • 8/2/2019 Hibernate Day2

    33/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    One Table per Concrete Class

  • 8/2/2019 Hibernate Day2

    34/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    QUERY FACILITY INHIBERNATE

    35

  • 8/2/2019 Hibernate Day2

    35/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Query Facility in Hibernate

    We can get data from the database using hibernate in 3

    different ways 1.Criteria Query

    2.HQL

    3.Native SQL

    36

  • 8/2/2019 Hibernate Day2

    36/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Criteria Query API

    37

  • 8/2/2019 Hibernate Day2

    37/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. 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 providing an example object whichcontain properties that has to be retrieved

    Supports aggregation methods (from Hibernate 3onwards)

    38

  • 8/2/2019 Hibernate Day2

    38/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Creating Criteria object

    Steps for a Simple Query

    1.Create Criteria object(org.hibernate.Criteria) viacreateCriteria() factory method of the Session

    2.Pass persistent object's class or the entity name to thecreateCriteria() method

    3Call list() method of the Criteria object

    Eg:

    1.Get all instances of Employee class and its subclasses

    Criteria crit = sess.createCriteria(Employee.class);

    List results = crit.list();

    39

  • 8/2/2019 Hibernate Day2

    39/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Selecting Fewer Rows using :-Restrictions

    To the Criteria query object add restrictions with add()

    method The add() method takes an Criterion object that

    represents an individual restriction

    Eg:2// Retrieve Employee data whose name has apattern

    Criteria crit = session.createCriteria(Employee.class);

    Criterion c= Restrictions.eq(name, Infy)

    crit.add(c);

    List results = crit.list();

    You can have any number of restriction for a Criteriaquery

    40

  • 8/2/2019 Hibernate Day2

    40/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Methods of Restriction Class

    Restrictions.eq(name, Infy)

    Restrictions.ne(name, NoName)

    Restrictions.like(name, Sa%)

    Restrictions.ilike(name, sa%)

    Restrictions.isNull(name);Restrictions.gt(price,new Double(30.0))

    Restrictions.between(age, new Integer(2), new

    Integer(10))

    41

  • 8/2/2019 Hibernate Day2

    41/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Logical Grouping - Restrictions

    Eg-3 :Retrieve Employee objects whose name has a

    pattern and whose exp is 10 or nullList people = sess.createCriteria(Employee.class)

    .add( Restrictions.like("name", R%") )

    .add( Restrictions.or(

    Restrictions.eq( exp", new Integer(10) ),

    Restrictions.isNull(exp)) )

    .list();

    42

  • 8/2/2019 Hibernate Day2

    42/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Pagination through ResultSet

    Hibernate handles the pagination

    Retrieving fixed number of objects

    Two methods of Criteria class

    setFirstResult() To set the first row in the result

    setMaxResults() The number of rows to beretrieved

    Eg:4 Using pagination

    Criteria crit = sess.createCriteria(Employee.class);

    crit.setFirstResult(2);crit.setMaxResults(50);

    List results = crit.list();

    43

  • 8/2/2019 Hibernate Day2

    43/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    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)

    sum(String propertyName) sum of the property values

    44

  • 8/2/2019 Hibernate Day2

    44/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. 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 criteriaobject using setProjection() method

    Eg:-The result will contain one object, an Integer that

    Holds the results of executing Avg(Salary)SQL

    statement

    Criteria crit = sess.createCriteria(Employee.class);

    crit.setProjection( Projections. avg (salary) );List results = crit.list();

    45

  • 8/2/2019 Hibernate Day2

    45/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Hibernate Query Language (HQL)

    46

  • 8/2/2019 Hibernate Day2

    46/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Hibernate Query Capabilities in 3.0

    Newly improved Hibernate Criteria Query API

    Hibernate Query Language (HQL)

    queries that are provided in the native SQL dialect of thedatabase is also supported

    47

  • 8/2/2019 Hibernate Day2

    47/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Hibernate Query Language (HQL)

    Very similar to SQL but less verbose

    Understands OO concepts like inheritance,polymorphism , association, aggregation, composition

    Selection

    from, as

    Projection

    select, elements

    Constraints

    where Associations and joins-

    outer join, full join, inner join, right outer join

    48

  • 8/2/2019 Hibernate Day2

    48/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Hibernate Query Language (HQL)

    Other constructs-> aggregate functions,

    expressions,

    group by clauses,

    order by clauses,

    polymorphic selections,

    sub-queries

    49

  • 8/2/2019 Hibernate Day2

    49/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Differences from SQL

    HQL is fully object-oriented and understands notions

    like, polymorphism ,association and inheritance Queries are case-insensitive,but for the names of Java

    classes and properties

    50

  • 8/2/2019 Hibernate Day2

    50/69

  • 8/2/2019 Hibernate Day2

    51/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. 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 localvariables

    52

  • 8/2/2019 Hibernate Day2

    52/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Join

    We may also assign aliases to elements of a collection

    of values or to associated entities, using a joinEg1. 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

    Eg:3 from Formula form full join form.parameter param

    53

  • 8/2/2019 Hibernate Day2

    53/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Join types supported

    inner join

    left outer join

    right outer join

    full join (not usually useful)

    54

  • 8/2/2019 Hibernate Day2

    54/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    select clause

    The select clause picks which properties & objects to

    return in the query result setselect spk

    from Event as evt

    inner join evt.speaker as spk

    Compact form

    select evt.speaker from Event evt

    55

  • 8/2/2019 Hibernate Day2

    55/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    select clause

    properties of any value type including the properties of

    component type can be returned by Queriesselect 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

    objects can be returned by Queries

    select mother, offspr, mate.name from DomesticCatas mother inner join mother.mate as mate left outer

    join mother.kittens as offspr

    56

  • 8/2/2019 Hibernate Day2

    56/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    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'

    57

  • 8/2/2019 Hibernate Day2

    57/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, 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 spkidproperty of the Event

    select evt

    from Event evt, Speaker spk

    where evt.spkid = spk.id

    Compound path expressions make the where clauseextremely powerful.

    from Event evt where evt.speaker.name is not null

    58

  • 8/2/2019 Hibernate Day2

    58/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Native SQL Query

    Native SQL is SQL in the native format for the database

    you are connected to, to performs operations like create,update, delete and select.

    Use createSQLQuery() method of session Object topass the query string.

    It returns a SQLQuery object Invoke the list() to get the data from the selected

    database table

    59

  • 8/2/2019 Hibernate Day2

    59/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Native SQL Query [contd]

    // Build SQL query

    {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);

    }

    60

    Demo Program

  • 8/2/2019 Hibernate Day2

    60/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Demo Program

    ID name salary joining_date

    1001 John 10000 12-jan-2009

    1002 Tommy 20000 13-mar-2008

    1003 Angel 23000 14-jun-2008

    1004 Joy 22000 23-apr-2007

    Table Name:EMPOLOYEE

    Entity class Name :Employee

    Program to find out the lowest salary amount

  • 8/2/2019 Hibernate Day2

    61/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Program to find out the lowest salary amountfrom the table (Aggregate Function)

    package demo;

    importjava.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;

    public class HibernateHQLMinFunction {

    public static void main(String[] args) {// TODO Auto-generated method stubSession sess = null;try {SessionFactory sf = new

    Configuration().configure().buildSessionFactory();sess = sf.openSession();

    Program to find out the lowest salary amount

  • 8/2/2019 Hibernate Day2

    62/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Program to find out the lowest salary amountfrom 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));

    }catch(Exception e){System.out.println(e.getMessage());

    }}

    Program to find out the lowest salary amount

  • 8/2/2019 Hibernate Day2

    63/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Program to find out the lowest salary amountfrom the table (Aggregate Function) [contd]

    Output:

    Min Salary Amount: 10000

    Demo 2: Select HQL Example

  • 8/2/2019 Hibernate Day2

    64/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Demo 2: Select HQL Example

    package demo;;

    import org.hibernate.Session;import org.hibernate.*;import org.hibernate.cfg.*;importjava.util.*;

    public class SelectHQLExample {public static void main(String[] args) {Session session = null;

    try{// prepare hibernate for use after reading the hibernate.cfg.xml

    SessionFactory sessionFactory = newConfiguration().configure().buildSessionFactory();

    session =sessionFactory.openSession();

    http://www.roseindia.net/hibernate/hibernatefromclauseexample.shtmlhttp://www.roseindia.net/hibernate/hibernatefromclauseexample.shtmlhttp://www.roseindia.net/hibernate/hibernatefromclauseexample.shtmlhttp://www.roseindia.net/hibernate/hibernatefromclauseexample.shtml
  • 8/2/2019 Hibernate Day2

    65/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Demo 2: Select HQL Example [contd]

    //Using from Clause

    String SQL_QUERY ="from Employee emp";Query query = session.createQuery(SQL_QUERY);for(Iterator it=query.iterate();it.hasNext();)

    {

    Employee emp=(Employee)it.next();System.out.println("ID: " + emp.getId());System.out.println("First Name: " + emp.getName());} session.close();

    }catch(Exception e){

    System.out.println(e.getMessage()); }finally{}}}

    Demo 3:Select HQL program->returns an array

  • 8/2/2019 Hibernate Day2

    66/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Demo 3:Select HQL program >returns an arrayof Object package demo

    import org.hibernate.Session;import org.hibernate.*;import org.hibernate.cfg.*;

    importjava.util.*;public class SelectClauseExample {public static void main(String[] args) {Session session = null;

    try{

    // prepare hibernate for use after reading the hibernate.cfg.xmlSessionFactory sessionFactory = new

    Demo 3:Select HQL program->returns an array

    http://www.roseindia.net/hibernate/hibernatefromclauseexample.shtmlhttp://www.roseindia.net/hibernate/hibernatefromclauseexample.shtml
  • 8/2/2019 Hibernate Day2

    67/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Configuration().configure().buildSessionFactory();session =sessionFactory.openSession();

    //Create Select Clause HQLString SQL_QUERY ="Select emp.id,emp.name," + emp.salary,emp.joining

    _date from Employee emp";Query query = session.createQuery(SQL_QUERY);

    for(Iterator it=query.iterate();it.hasNext();){Object[] row = (Object[]) it.next();System.out.println("ID: " + row[0]);System.out.println("Name: " + row[1]);System.out.println("Amount: " + row[2]);

    } session.close();}catch(Exception e){System.out.println(e.getMessage());

    }finally{} }}

    Demo 3:Select HQL program >returns an arrayof Object [contd]

    S

  • 8/2/2019 Hibernate Day2

    68/69

    We enable you to leverage knowledgeanytime, anywhere!

    Infosys Technologies Ltd.

    2008, Infosys Technologies Ltd. Confidential

    Summary

    Introduction- Introduction to ORM & Hibernate

    Hibernate Architecture and FrameworkHibernate Instance States ,Lifecycle Operation

    Hibernate Configurations

    Primary Key Generation, Composite Key, Hibernate Data

    Types

    OR Mapping-Relations and Inheritance

    Criteria Query API, HQL & native SQL

    69

  • 8/2/2019 Hibernate Day2

    69/69

    Infosys Technologies Ltd.

    Thank You


Recommended