+ All Categories
Home > Documents > 1 Hibernate

1 Hibernate

Date post: 07-Apr-2018
Category:
Upload: jesinth-nirmal
View: 228 times
Download: 0 times
Share this document with a friend

of 36

Transcript
  • 8/3/2019 1 Hibernate

    1/36

    Hibernate

    Hibernate 3.0, the latest Open Source persistence technology at the heart of J2EE EJB 3.0 is

    available for download from Hibernet.org. The Hibernate 3.0 core is 68,549 lines of Java code

    together with 27,948 lines of unit tests, all freely available under the LGPL, and has been indevelopment for well over a year. Hibernate maps the Java classes to the database tables. It

    also provides the data query and retrieval facilities that significantly reduce the development

    time. Hibernate is not the best solutions for data centric applications that only uses the

    stored-procedures to implement the business logic in database. It is most useful with object-

    oriented domain modes and business logic in the Java-based middle-tier. Hibernate allows

    transparent persistence that enables the applications to switch any database. Hibernate can

    be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using

    EJB session beans.

    Features of Hibernate

    Hibernate 3.0 provides three full-featured query facilities: Hibernate Query Language,the newly enhanced Hibernate Criteria Query API, and enhanced support for queries

    expressed in the native SQL dialect of the database.

    Filters for working with temporal (historical), regional or permitted data.

    Enhanced Criteria query API: with full support for projection/aggregation and subselects.

    Runtime performance monitoring: via JMX or local Java API, including a second-level cache

    browser.

    Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate 3.0,

    including mapping editor, interactive query prototyping, schema reverse engineering

    tool.

    Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the

    applications for free.

    Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture

    can be used in the clustered environments.

    Less Development Time: Hibernate reduces the development timings as it supports

    inheritance, polymorphism, composition and the Java Collection framework.

    Automatic Key Generation: Hibernate supports the automatic generation of primary key for

    your.

    JDK 1.5 Enhancements: The new JDK has been released as a preview earlier this year and

    we expect a slow migration to the new 1.5 platform throughout 2004. While Hibernate3

    still runs perfectly with JDK 1.2, Hibernate3 will make use of some new JDK features.

    JSR 175 annotations, for example, are a perfect fit for Hibernate metadata and we will

    embrace them aggressively. We will also support Java generics, which basically boils

    down to allowing type safe collections.

    EJB3-style persistence operations: EJB3 defines the create() and merge() operations,

  • 8/3/2019 1 Hibernate

    2/36

    which are slightly different to Hibernate's saveOrUpdate() and saveOrUpdateCopy()

    operations. Hibernate3 will support all four operations as methods of the Session

    interface.

    Hibernate XML binding enables data to be represented as XML and POJOs

    interchangeably. The EJB3 draft specification support for POJO persistence and annotations.

    Hibernate ArchitectureIn this lesson you will learn the architecture of Hibernate. The following diagram describes

    the high level architecture of hibernate:

    The above diagram shows that Hibernate is using the database and configuration data to

    provide persistence services (and persistent objects) to the application.

    To use Hibernate, it is required to create Java classes that represents the table in the

    database and then map the instance variable in the class with the columns in the database.

    Then Hibernate can be used to perform operations on the database like select, insert, update

    and delete the records in the table. Hibernate automatically creates the query to perform

    these operations.

    Hibernate architecture has three main components:

    Connection Management

    Hibernate Connection management service provide efficient management of the

    database connections. Database connection is the most expensive part of interacting

    with the database as it requires a lot of resources of open and close the database

  • 8/3/2019 1 Hibernate

    3/36

    connection.

    Transaction management:

    Transaction management service provide the ability to the user to execute more than

    one database statements at a time.

    Object relational mapping:Object relational mapping is technique of mapping the data representation from an

    object model to a relational data model. This part of the hibernate is used to select,

    insert, update and delete the records form the underlying table. When we pass an

    object to a Session.save() method, Hibernate reads the state of the variables of that

    object and executes the necessary query.

    Hibernate is very good tool as far as object relational mapping is concern, but in terms of

    connection management and transaction management, it is lacking in performance and

    capabilities. So usually hibernate is being used with other connection management and

    transaction management tools. For example apache DBCP is used for connection pooling

    with the Hibernate.

    Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only

    uses the object relational mapping component. While in "Full Cream" architecture all the

    three component Object Relational mapping, Connection Management and Transaction

    Management) are used.

    Configuring Hibernate

    In this application Hibernate provided connection pooling and transaction management is

    used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and

    setup required environment.

    Here is the code:

    com.mysql.jdbc.Driver

    jdbc:mysql://localhost/hibernatetutorial root 10 true org.hibernate.dialect.MySQLDialect

    update

  • 8/3/2019 1 Hibernate

    4/36

    In the above configuration file we specified to use the "hibernatetutorial" which is running

    on localhost and the user of the database is root with no password. The dialect property

    is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL

    Database. Hibernate supports many database. With the use of the Hibernate (Object/

    Relational Mapping and Transparent Object Persistence for Java and SQL Databases), we canuse the following databases dialect type property:

    DB2 - org.hibernate.dialect.DB2Dialect

    HypersonicSQL - org.hibernate.dialect.HSQLDialect

    Informix - org.hibernate.dialect.InformixDialect

    Ingres - org.hibernate.dialect.IngresDialect

    Interbase - org.hibernate.dialect.InterbaseDialect

    Pointbase - org.hibernate.dialect.PointbaseDialect

    PostgreSQL - org.hibernate.dialect.PostgreSQLDialect Mckoi SQL - org.hibernate.dialect.MckoiDialect

    Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect

    MySQL - org.hibernate.dialect.MySQLDialect

    Oracle (any version) - org.hibernate.dialect.OracleDialect

    Oracle 9 - org.hibernate.dialect.Oracle9Dialect

    Progress - org.hibernate.dialect.ProgressDialect

    FrontBase - org.hibernate.dialect.FrontbaseDialect

    SAP DB - org.hibernate.dialect.SAPDBDialect

    Sybase - org.hibernate.dialect.SybaseDialect

    Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect

    The property is the mapping for our contact table.

    Writing First Persistence Class

    Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We

    can configure the variables to map to the database column.

    Mapping the Contact Object to the Database Contact table

    The file contact.hbm.xml is used to map Contact Object to the Contact table in thedatabase. Here is the code for contact.hbm.xml:

  • 8/3/2019 1 Hibernate

    5/36

    Setting Up MySQL Database

    In the configuration file(hibernate.cfg.xml) we have specified to use hibernatetutorial

    database running on localhost. So, create the databse ("hibernatetutorial") on the MySQL

    server running on localhost.

    Developing Code to Test Hibernate example

    Now we are ready to write a program to insert the data into database. We should first

    understand about the Hibernate's Session. Hibernate Session is the main runtime interface

    between a Java application and Hibernate. First we are required to get the Hibernate

    Session.SessionFactory allows application to create the Hibernate Sesssion by reading the

    configuration from hibernate.cfg.xml file. Then the save method on session object is used

    to save the contact information to the database:

    session.save(contact)

    We created contact.hbm.xml to map Contact Object to the Contact table in the database.

    Now let's understand the each component of the mapping file.

    To recall here is the content of contact.hbm.xml:

    Hibernate mapping documents are simple xml documents. Here are important elements of the

    mapping file:.

    element

    The first or root element of hibernate mapping document is element.Between the tag class element(s) are present.

    element

    The element maps the class object with corresponding entity in the database. It

    also tells what table in the database has to access and what column in that table it should

    use. Within one element, several mappings are possible.

    element

  • 8/3/2019 1 Hibernate

    6/36

    The element in unique identifier to identify and object. In fact element map with the

    primary key of the table. In our code :

    primary key maps to the ID field of the table CONTACT. The attributes of the id element are:

    name: The property name used by the persistent class.

    column: The column used to store the primary key value.

    type: The Java data type used.

    unsaved-value: This is the value used to determine if a class has been made persistent.

    If the value of the id attribute is null, then it means that this object has not been

    persisted.

    element

    The methodis used to generate the primary key for the new record. Here is some

    of the commonly used generators :

    *Increment - This is used to generate primary keys of type long, short or int that are unique

    only. It should not be used in the clustered deployment environment.

    * Sequence - Hibernate can also use the sequences to generate the primary key. It can be used

    with DB2, PostgreSQL, Oracle, SAP DB databases.

    * Assigned - Assigned method is used when application code generates the primary key.

    element

    The property elements define standard Java attributes and their mapping into database schema.

    The property element supports the column child element to specify additional properties, such

    as the index name on a column or a specific column type.

    Hibernate generator element generates the primary key for new record. There are many options

    provided by the generator method to be used in different situations.

    1. The element

    2. This is the optional element under element. The element is used to specify

    the class name to be used to generate the primary key for new record while saving a new

    record. The element is used to pass the parameter (s) to the class. Here is the

    example of generator element from our first application:

    In this case element do not generate the primary key and it is required to set the

    primary key value before calling save() method.

    3. Here are the list of some commonly used generators in hibernate:

    Generator Description

    increment

    It generates identifiers of type long, short or int that are unique only when no other

    process is inserting data into the same table. It should not the used in the clustered

    environment.

    identityIt supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL.

    The returned identifier is of type long, short or int.

    sequenceThe sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a

    generator in Interbase. The returned identifier is of type long, short or int

    The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long,

  • 8/3/2019 1 Hibernate

    7/36

    hilo short or int, given a table and column (by default hibernate_unique_key and next_hi

    respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are

    unique only for a particular database. Do not use this generator with connections enlisted

    with JTA or with a user-supplied connection.seqhilo

    The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long,

    short or int, given a named database sequence.

    uuidThe uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string,unique within a network (the IP address is used). The UUID is encoded as a string of

    hexadecimal digits of length 32.

    guid It uses a database-generated GUID string on MS SQL Server and MySQL.

    nativeIt picks identity, sequence or hilo depending upon the capabilities of the underlying

    database.

    assignedlets the application to assign an identifier to the object before save() is called. This is the

    default strategy if no element is specified.

    selectretrieves a primary key assigned by a database trigger by selecting the row by some unique

    key and retrieving the primary key value.

    foreignuses the identifier of another associated object. Usually used in conjunction with a primary key association.

    As we have seen in the last section that the increment class generates identifiers of type long,short or int that are unique only when no other process is inserting data into the same table. Inthis lesson I will show you how to write running program to demonstrate it. You should notuse this method to generate the primary key in case of clustured environment.

    ), write the program to test it out.

    Create Table in the mysql database:

    User the following sql statement to create a new table in the database.CREATE TABLE `book` (

    `id` int(11) NOT NULL default '0',`bookname` varchar(50) default NULL,PRIMARY KEY (`id`)) TYPE=MyISAM

    "book".

    /*** Java Class to map to the database Book table*/

    package roseindia.tutorial.hibernate;

    public classBook { private longlngBookId;private String strBookName;

    public longgetLngBookId() {return lngBookId;

    }

    public voidsetLngBookId(long lngBookId) {this.lngBookId = lngBookId;

  • 8/3/2019 1 Hibernate

    8/36

    }

    public String getStrBookName() {return strBookName;

    }

    public voidsetStrBookName(String strBookName) {this.strBookName = strBookName;

    }

    }

    Adding Mapping entries to contact.hbm.xml

    Add the following mapping code into the contact.hbm.xml file

    Note that we have used increment for the generator class. *After adding the entries to the xml filecopy it to the bin directory of your hibernate eclipse project(this step is required if you are using eclipse).

    Write the client program and test it out

    Here is the code of our client program to test the application.

    /**

    * Example to show the increment class of hibernate generator element to* automatically generate the primay key*/

    package roseindia.tutorial.hibernate;

    //Hibernate Importsimport org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;

    public classIdIncrementExample { public static voidmain(String[] args) {

    Session session = null;

    try{

    // This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure()

    .buildSessionFactory();session =sessionFactory.openSession();org.hibernate.Transaction tx = session.beginTransaction();

    //Create new instance of Contact and setvalues in it by reading them from form object

    System.out.println("Inserting Book object into database..");Book book = new Book();

  • 8/3/2019 1 Hibernate

    9/36

    book.setStrBookName("Hibernate Tutorial");session.save(book);System.out.println("Book object persisted to the database.");

    tx.commit();session.flush();session.close();

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

    }finally{}

    }

    }

    To test the program Select Run->Run As -> Java Application from the eclipse menu bar. This will

    create a new record into the book table.

    Update Query:

    public class UpdateExample {/*** @param args*/

    public static voidmain(String[] args) {// TODO Auto-generated method stubSession sess = null;try {SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();Transaction tr = sess.beginTransaction();Insurance ins = (Insurance)sess.get(Insurance.class, new Long(1));ins.setInsuranceName("Jivan Dhara");ins.setInvestementAmount(20000);ins.setInvestementDate(new Date());

    sess.update(ins);tr.commit();sess.close();System.out.println("Update successfully!");

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

    }}

    }

    Output:

    log4j:WARN No appenders could be found for logger(org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: select insurance0_.ID as ID0_0_, insurance0_.insurance_nameas insurance2_0_0_, insurance0_.invested_amount as invested3_0_0_,insurance0_.investement_date as investem4_0_0_ from insurance insurance0_where insurance0_.ID=?

    Hibernate: update insurance set insurance_name=?, invested_amount=?,investement_date=? where ID=?

  • 8/3/2019 1 Hibernate

    10/36

    Update successfully!

    public static voidmain(String[] args) {

    // TODO Auto-generated method stubSession sess = null;try {SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String hql = "delete from Insurance insurance where id = 2";Query query = sess.createQuery(hql);int row = query.executeUpdate();if (row == 0){System.out.println("Doesn't deleted any row!");

    }else{System.out.println("Deleted Row: " + row);

    }sess.close();

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

    }}

    }

    Download this code.

    Output:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: delete from insurance where ID=2

    Deleted Row: 1

    Hibernate Query Language or HQL for short is extremely powerful query language. HQL is much like

    SQL and are case-insensitive, except for the names of the Java Classes and properties. Hibernate

    Query Language is used to execute queries against database. Hibernate automatically generates the

    sql query and execute it against underlying database if HQL is used in the application. HQL is based

    on the relational object models and makes the SQL object oriented. Hibernate Query Language

    uses Classes and properties instead of tables and columns. Hibernate Query Language is extremely

    powerful and it supports Polymorphism, Associations, Much less verbose than SQL.

    There are other options that can be used while using Hibernate. These are Query By Criteria (QBC)

    and Query BY Example (QBE) using Criteria API and the Native SQL queries. In this lesson we will

    understand HQL in detail.

    Why to use HQL?

    Full support for relational operations: HQL allows representing SQL queries in the form of objects.

    Hibernate Query Language uses Classes and properties instead of tables and columns.

    Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is

    easy to use. This elemenates the need of creating the object and populate the data from result

  • 8/3/2019 1 Hibernate

    11/36

    set.

    Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the

    query results along with all the child objects if any.

    Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the

    applications.Support for Advance features: HQL contains many advance features such as pagination, fetch join

    with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection,

    Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.

    Database independent: Queries written in HQL are database independent (If database supports

    the underlying feature).

    Understanding HQL Syntax

    Any Hibernate Query Language may consist of following elements:

    Clauses

    Aggregate functions

    Subqueries

    Clauses in the HQL are:

    from

    select

    where

    order by

    group by

    Aggregate functions are:

    avg(...), sum(...), min(...), max(...)

    count(*)

    count(...), count(distinct ...), count(all...)

    Subqueries

    Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the

    underlying database supports it.

    Adding mappings into contact.hbm.xml file

    Add the following code into contact.hbm.xml file.

  • 8/3/2019 1 Hibernate

    12/36

    Now we have created the POJO class and necessary mapping into contact.hbm.xml file.

    In this example you will learn how to use the HQL from clause. The from clause is the simplest

    possible Hibernate Query. Example of from clause is:from Insurance insurance

    Here is the full code of the from clause example:

    /*** Select HQL Example*/

    public class SelectHQLExample {

    public static voidmain(String[] args) {Session session = null;

    try{

    // This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session =sessionFactory.openSession();

    //Using from ClauseString SQL_QUERY ="from Insurance insurance";Query query = session.createQuery(SQL_QUERY);for(Iterator it=query.iterate();it.hasNext();){

    Insurance insurance=(Insurance)it.next();System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("FirstName: " + insurance.getInsuranceName());

    }session.close();

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

    }finally{}

    }

    }

    To run the example select Run-> Run As -> Java Application from the menu bar. Following out is

    displayed in the Eclipse console:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: select insurance0_.ID as col_0_0_ from insurance insurance0_

    ID: 1Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amountas invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?

    First Name: Car Insurance

    ID: 2

    Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amountas invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?

    First Name: Life Insurance

  • 8/3/2019 1 Hibernate

    13/36

    Hibernate Select Clause.

    The select clause picks up objects and properties to return in the query result set. Here is the query:

    Select insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount,

    insurance.investementDate from Insurance insurance

    which selects all the rows (insurance.lngInsuranceId, insurance.insuranceName,

    insurance.investementAmount, insurance.investementDate) from Insurance table.

    Hibernate generates the necessary sql query and selects all the records from Insurance table. Here is

    the code of our java file which shows how select HQL can be used:

    /**

    * HQL Select Clause Example*/

    public class SelectClauseExample { public static voidmain(String[] args) {Session session = null;

    try{// This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session =sessionFactory.openSession();

    //Create Select Clause HQLString SQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," +"insurance.investementAmount,insurance.investementDate from Insurance insurance";

    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{}

    }

    }

    To run the example select Run-> Run As -> Java Application from the menu bar. Following out is

    displayed in the Eclipse console:

    Hibernate: select insurance0_.ID as col_0_0_, insurance0_.insurance_name as col_1_0_,

    insurance0_.invested_amount as col_2_0_, insurance0_.investement_date as col_3_0_ from insuranceinsurance0_

    ID: 1

    Name: Car Insurance

    Amount: 1000

    ID: 2

    Name: Life Insurance

  • 8/3/2019 1 Hibernate

    14/36

    Amount: 100

    Hibernate supports multiple aggregate functions. when they are used in HQL queries, they return

    an aggregate value (such as sum, average, and count) calculated from property values of all objects

    satisfying other query criteria. These functions can be used along with the distinct and all options,to return aggregate values calculated from only distinctvalues and all values (except null values),

    respectively. Following is a list of aggregate functions with their respective syntax; all of them are self-

    explanatory.

    count( [ distinct | all ] object | object.property )

    count(*) (equivalent to count(all ...), counts null values also)

    sum ( [ distinct | all ] object.property)

    avg( [ distinct | all ] object.property)

    max( [ distinct | all ] object.property)

    min( [ distinct | all ] object.property)

    Here is thejava code for counting the records from insurance table:

    public static voidmain(String[] args) {// TODO Auto-generated method stub

    Session sess = null;int count = 0;try {SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String SQL_QUERY = "select count(*)

    from Insurance insurance group by insurance.lngInsuranceId";Query query = sess.createQuery(SQL_QUERY);for (Iterator it = query.iterate(); it.hasNext();) {it.next();count++;

    }System.out.println("Total rows: " + count);

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

    }}

    }

    Download this code.

    Output:

    log4j:WARN No appenders could be found for logger(org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: select count(*) as col_0_0_ from insuranceinsurance0_ group by insurance0_.ID

    Total rows: 6

  • 8/3/2019 1 Hibernate

    15/36

    Where Clause is used to limit the results returned from database. It can be used with aliases and if

    the aliases are not present in the Query, the properties can be referred by name. For example:

    from Insurance where lngInsuranceId='1'

    Where Clause can be used with or without Select Clause. Here the example code:

    /*** HQL Where Clause Example* Where Clause With Select Clause Example*/

    public class WhereClauseExample { public static voidmain(String[] args) {Session session = null;

    try{// This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure()

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

    System.out.println("*****************************");System.out.println("Query using Hibernate Query Language");

    //Query using Hibernate Query LanguageString SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='1

    '";Query query = session.createQuery(SQL_QUERY);for(Iterator it=query.iterate();it.hasNext();){Insurance insurance=(Insurance)it.next();System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("Name: "+ insurance. getInsuranceName()); }

    System.out.println("*******************************");System.out.println("Where Clause With Select Clause");

    //Where Clause With Select ClauseSQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," +"insurance.investementAmount,insurance.investementDate from Insurance

    insurance "+ " where insurance.lngInsuranceId='1'";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("*******************************");

    session.close();}catch(Exception e){

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

    }

    }

    The Criteria interface allows to create and execute object-oriented queries. It is powerful alternative

    to the HQL but has own limitations. Criteria Query is used mostly in case of multi criteria search

  • 8/3/2019 1 Hibernate

    16/36

    screens, where HQL is not very effective.

    org.hibernate.Criteria is used to create the criterion for the search. The org.hibernate.Criteria interface

    represents a query against a persistent class. The Session is a factory for Criteria instances. Here is a

    simple example of Hibernate Criterial Query:

    /**Hibernate Criteria Query Example */ public classHibernateCriteriaQueryExample {

    public static voidmain(String[] args) {Session session = null;try {// This step will read hibernate.cfg.xml and prepare hibernate for use

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    session = sessionFactory.openSession();//Criteria Query ExampleCriteria crit = session.createCriteria(Insurance.class);List insurances = crit.list();for(Iterator it = insurances.iterator();it.hasNext();){Insurance insurance = (Insurance) it.next();

    System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("Name: " + insurance.getInsuranceName());

    }session.close();

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

    } finally {}

    }

    }

    The above Criteria Query example selects all the records from the table and displays on the console.

    In the above code the following code creates a new Criteria instance, for the class Insurance:

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

    The code:

    List insurances = crit.list();

    creates the sql query and execute against database to retrieve the data.

    Criteria Query Examples

    can be used with the help of Restrictions to restrict the records fetched from database.

    Criteria Interface provides the following methods:

    Method Description

    add The Add method adds a Criterion to constrain the results to be retrieved.

    addOrder Add an Order to the result set.

    createAlias Join an association, assigning an alias to the joined entity

    createCriteria This method is used to create a new Criteria, "rooted" at the associated entity.

    setFetchSize This method is used to set a fetch size for the underlying JDBC query.

    setFirstResult This method is used to set the first result to be retrieved.

    setMaxResults This method is used to set a limit upon the number of objects to be retrieved.

  • 8/3/2019 1 Hibernate

    17/36

    uniqueResult This method is used to instruct the Hibernate to fetch and return the uniquerecords from database.

    Class Restriction provides built-in criterion via static factory methods. Important methods of the

    Restriction class are:

    Method Description

    Restriction.allEq

    This is used to apply an "equals" constraint to each property in the key setof a Map

    Restriction.between

    This is used to apply a "between" constraint to the named property

    Restriction.eq

    This is used to apply an "equal" constraint to the named property

    Restriction.ge

    This is used to apply a "greater than or equal" constraint to the namedproperty

    Restriction.gt

    This is used to apply a "greater than" constraint to the named property

    Restriction.idEq This is used to apply an "equal" constraint to the identifier property

    Restriction.ilike

    This is case-insensitive "like", similar to Postgres ilike operatorRestriction.in This is used to apply an "in" constraint to the named property

    Restriction.isNotNull This is used to apply an "is not null" constraint to the named property

    Restriction.isNull This is used to apply an "is null" constraint to the named property

    Restriction.le This is used to apply a "less than or equal" constraint to the named property

    Restriction.like This is used to apply a "like" constraint to the named property

    Restriction.lt This is used to apply a "less than" constraint to the named property

    Restriction.ltProperty This is used to apply a "less than" constraint to two properties

    Restriction.ne This is used to apply a "not equal" constraint to the named property

    Restriction.neProperty This is used to apply a "not equal" constraint to two properties

    Restriction.not This returns the negation of an expression

    Restriction.or

    This returns the disjuction of two expressionsHere is an example code that shows how to use Restrictions.like method and restrict the maximum

    rows returned by query by setting the Criteria.setMaxResults() value to 5.

    /**Hibernate Criteria Query Example**/ public class HibernateCriteriaQueryExample2 { public static voidmain(String[] args) {

    Session session = null;try {// This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure()

    .buildSessionFactory();

    session = sessionFactory.openSession();//Criteria Query ExampleCriteria crit = session.createCriteria(Insurance.class);crit.add(Restrictions.like("insuranceName", "%a%")); //Like conditioncrit.setMaxResults(5); //Restricts the max rows to 5

    List insurances = crit.list();for(Iterator it = insurances.iterator();it.hasNext();){Insurance insurance = (Insurance) it.next();System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("Name: " + insurance.getInsuranceName());

  • 8/3/2019 1 Hibernate

    18/36

    }session.close();

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

    } finally {}

    }}

    Hibernate's Built-in criterion: Between (using Integer)

    In this tutorial,, you will learn to use "between" with the Integer class. "Between" when used with the

    Integer object, It takes three parameters e.g. between("property_name",min_int,max_int).

    Restriction class provides built-in criterion via static factory methods. One important method of the

    Restriction class is between: which is used to apply a "between" constraint to the named property

    Here is the code of the class using "between" with the Integer class :

    Hibernate Criteria Query Example

    public classHibernateCriteriaQueryBetweenTwoInteger {

    public static voidmain(String[] args) {

    Session session = null;

    try {

    // This step will read hibernate.cfg.xml and prepare hibernate for use

    SessionFactory sessionFactory = new Configuration().configure()

    .buildSessionFactory();

    session = sessionFactory.openSession();

    //Criteria Query ExampleCriteria crit = session.createCriteria(Insurance.class);

    crit.add(Expression.between("investementAmount", new Integer(1000),

    new Integer(2500))); //Between condition

    crit.setMaxResults(5); //Restricts the max rows to 5

    List insurances = crit.list();

    for(Iterator it = insurances.iterator();it.hasNext();){

    Insurance insurance = (Insurance) it.next();

    System.out.println("ID: " + insurance.getLngInsuranceId());

    System.out.println("Name: " + insurance.getInsuranceName());

    System.out.println("Amount: " + insurance.getInvestementAmount());

    }

    session.close();

    } catch (Exception e) {

    System.out.println(e.getMessage());

    } finally {

    }

    }

    }

  • 8/3/2019 1 Hibernate

    19/36

    Download this code:

    Output:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: select this_.ID as ID0_0_, this_.insurance_name as insurance2_0_0_, this_.invested_amount as invested3_0_0_, this_.investement_date as investem4_0_0_ from insurance this_ where this_.invested_amount between ? and ? limit ?

    ID: 1

    Name: Car Insurance

    Amount: 1000

    ID: 4

    Name: Car Insurance

    Amount: 2500

    ID: 7

    Name: Travel Insurance

    Amount: 2000

    Hibernate's Built-in criterion: Between (using with Date)

    In this section, you will learn to use "between" i.e.one of the built-in hibernate criterions. Restriction

    class provides built-in criterion via static factory methods. One important method of the Restriction

    class is between: which is used to apply a "between" constraint to the named property

    In this tutorial, "Between" is used with the date object. It takes three parameters e.g.

    between("property_name",startDate,endDate)

    Here is the code of the class using "between" with the Date class :

    Hibernate Criteria Query Example **/

    public classHibernateCriteriaQueryBetweenDate {

    public static voidmain(String[] args) {

    Session session = null;

    try {

    // This step will read hibernate.cfg.xml and prepare hibernate for use

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    session = sessionFactory.openSession();

    //Criteria Query Example

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

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    Date startDate = (Date)format.parse("2005-01-01 00:00:00");

    Date endDate = (Date)format.parse("2005-03-03 00:00:00");

  • 8/3/2019 1 Hibernate

    20/36

    crit.add(Expression.between("investementDate", new Date(startDate.getTime()), new Date(endDate.getTime()))); //Between date condn

    crit.setMaxResults(5); //Restricts the max rows to 5

    List insurances = crit.list();

    for(Iterator it = insurances.iterator();it.hasNext();){

    Insurance insurance = (Insurance) it.next();System.out.println("ID: " + insurance.getLngInsuranceId());

    System.out.println("Name: " + insurance.getInsuranceName());

    System.out.println("Amount: " + insurance.getInvestementAmount());

    System.out.println("Date: " + insurance.getInvestementDate());

    }

    session.close();

    } catch (Exception e) {

    System.out.println(e.getMessage());

    } finally {

    }

    }

    }

    Download this code:

    Output:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: select this_.ID as ID0_0_, this_.insurance_name as insurance2_0_0_, this_.invested_amountas invested3_0_0_, this_.investement_date as investem4_0_0_ from insurance this_ where

    this_.investement_date between ? and ? limit ?ID: 1

    Name: Car Insurance

    Amount: 1000

    Date: 2005-01-05 00:00:00.0

    ID: 4

    Name: Car Insurance

    Amount: 2500

    Date: 2005-01-01 00:00:00.0

    Insert Data into Database Using Hibernate Native SQL

    In this example we will show you how you can use Native SQL with hibernate. You will learn how to

    use Native to insert data into database. Native SQL is handwritten SQL for all database operations like

    insert, update, delete and select.

  • 8/3/2019 1 Hibernate

    21/36

    Hibernate provides a powerful query language Hibernate Query Language that is expressed in a

    familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports

    native SQL statements. It also selects an effective way to perform a database manipulation task for an

    application.

    Step1: Create hibernate native sql for inserting data into database.

    Hibernate Native uses only the Hibernate Core for all its functions. The code for a class that will be

    saved to the database is displayed below:

    package hibernateexample;

    import javax.transaction.*;import org.hibernate.Transaction;import org.hibernate.*;import org.hibernate.criterion.*;import org.hibernate.cfg.*;import java.util.*;

    public classHibernateNativeInsert { public static voidmain(String args[]){

    Session sess = null;try{sess = HibernateUtil.currentSession();Transaction tx = sess.beginTransaction();Studentdetail student = new Studentdetail();student.setStudentName("Amardeep Patel");student.setStudentAddress("rohini,sec-2, delhi-85");student.setEmail("[email protected]");sess.save(student);System.out.println("Successfully data insert in database");tx.commit();

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

    }finally{sess.close();

    }}

    }

    Step 2: Create session factory 'HibernateUtil.java'.

    Here is the code of session Factory:

    package hibernateexample;

    import java.sql.*;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import java.io.*;

  • 8/3/2019 1 Hibernate

    22/36

    public classHibernateUtil {

    public static finalSessionFactory sessionFact;static {

    try {// Create the SessionFactory from hibernate.cfg.xmlsessionFact = new Configuration().configure().buildSessionFactory();

    }catch(Throwable e) {System.out.println("SessionFactory creation failed." + e);throw new ExceptionInInitializerError(e);

    }}

    public static finalThreadLocal session = new ThreadLocal();

    public staticSession currentSession() throws HibernateException {Session sess = (Session) session.get();// Open a new Session, if this thread has none yetif(sess == null){sess = sessionFact.openSession();

    // Store it in the ThreadLocal variablesession.set(sess);}return sess;

    } public static voidSessionClose() throws Exception {

    Session s = (Session) session.get();if (s != null)s.close();

    session.set(null);}

    }

    Step 3: Hibernate native uses the Plain Old Java Objects (POJOs) classes to map to the database

    table. We can configure the variables to map to the database column. Here is the code

    for "Studenetdetail.java":

    package hibernateexample;

    public classStudentdetail {private String studentName;private String studentAddress;private String email; private intid;

    public String getStudentName(){return studentName;

    }

    public voidsetStudentName(String studentName){this.studentName = studentName;

    }

    public String getStudentAddress(){return studentAddress;

  • 8/3/2019 1 Hibernate

    23/36

    }

    public voidsetStudentAddress(String studentAddress){this.studentAddress = studentAddress;

    }

    public String getEmail(){return email;

    }

    public voidsetEmail(String email){this.email = email;

    }

    public intgetId(){return id;

    }

    public voidsetId(int id){

    this.id = id;}

    }

    Here is the output:

    Associations and Joins

    This section includes a brief introduction about Associations and Joins along with examples.

    Association mappings: Association mappings comes in the list of the most difficult thing to get right.

    This section includes the canonical cases one by one. Here we starts the section from unidirectional

    mappings and comes to the bi-directional cases.

    We'll include the classification of associations that whether they map or not to an intervening jointable and by multiplicity.

    Here we are not using the Nullable foreign keys since these keys do not require good practice in

    traditional data modeling. Hibernate does not require the foreign keys since mappings work even if

    we drop the nullability constraints.

    Hibernate HQL Inner Join

    Hibernate's HQL language is not capable for handling the "inner join on" clauses. If our domain entity

  • 8/3/2019 1 Hibernate

    24/36

    model includes relationships defined between the related objects then the query like this

    Query query = session.createQuery("from Car car inner join Owner owner where

    owner.Name ='Vinod'");

    will work. HQL keeps the information of joining the Car and Owner classes according to the

    association mapping contained in the hbm.xml file. Since the association information is defined inthe mapping file so there is no need to stipulate the join in the query. In the above query "from Car

    car where car.Owner.Name='Vinod'" will work too. Initialization of the collections and many-to-one

    mapping requires the explicit joins just to avoid lazy load errors.

    A unidirectional one-to-many association on a foreign key is rarely required.

    A unidirectional one-to-many association on a foreign key is rarely required.

  • 8/3/2019 1 Hibernate

    25/36

    Here is the hibernate code:

    In this example first we create the session object with the help of the SessionFactory interface. Then

    we use the createQuery() method of the Session object which returns a Query object. Now we use

    the openSession() method of the SessionFactory interface simply to instantiate the Session object.

    And the we retrieve the data from the database store it in that Query object and iterate this object

    with the help of Iterator and finally displays the requested data on the console.

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

    public classJoin { public static voidmain(String[] args) {

    // TODO Auto-generated method stubSession sess = null;try{SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String sql_query = "from Product p inner join p.dealer as d";Query query = sess.createQuery(sql_query);Iterator ite = query.list().iterator();System.out.println("Dealer Name\t"+"Product Name\t"+"Price");while ( ite.hasNext() ) {

    Object[] pair = (Object[]) ite.next();Product pro = (Product) pair[0];Dealer dea = (Dealer) pair[1];System.out.print(pro.getName());System.out.print("\t"+dea.getName());

    System.out.print("\t\t"+pro.getPrice());System.out.println();

    }sess.close();

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

    }

    }

    }

    Output:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: select product0_.id as id1_0_, dealer1_.id as id0_1_, product0_.name as name1_0_, product0_.didas did1_0_, product0_.price as price1_0_, dealer1_.name as name0_1_ from Product product0_ inner joinDealer dealer1_ on product0_.did=dealer1_.id

    Dealer Name Product Name Price

    Computer Agrawal 23000.0

  • 8/3/2019 1 Hibernate

    26/36

    Keyboard Agrawal 1500.0

    Computer Agrawal 100.0

    Hibernate Aggregate Functions(Associations and Joins)This example tries to make understand about the aggregate function of Hibernate with the help of

    example.

    In Hibernate HQL queries are capable of returning the results of the aggregate functions on

    properties. Collections can also be used with the aggregate functions with the select clause.

    Aggregate functions supports the following functions:

    min(...), max(...), sum(...), avg(...).

    count(*)

    count(distinct...), count(all..), count(...)

    The distinct and all keywords used above are identical as in SQL.

    A unidirectional one-to-many association on a foreign key is rarely required.

    A unidirectional one-to-many association on a foreign key is rarely required.

  • 8/3/2019 1 Hibernate

    27/36

    In this example first we create the session object with the help of the SessionFactory interface. Then

    we use the createQuery() method of the Session object which returns a Query object. Now we use

    the openSession() method of the SessionFactory interface simply to instantiate the Session object.

    And the we retrieve the data from the database store it in that Query object and iterate this object

    with the help of Iterator and finally displays the requested data on the console.

    Here is the hibernate code:

    public class AggregateFunctionExample {

    /*** @param args*/

    public static voidmain(String[] args) {// TODO Auto-generated method stubSession sess = null;try{SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String sql_query = "select d.name,p.name,sum(p.price) as totalprice from Product

    p join p.dealer d group by p.name";Query query = sess.createQuery(sql_query);System.out.println("Dealer Name\t"+"Product Name\t"+"Price");for(Iterator it=query.iterate();it.hasNext();){Object[] row = (Object[]) it.next();

    System.out.print(row[0]);System.out.print("\t\t"+row[1]);System.out.print("\t"+row[2]);System.out.println();

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

    }}

    }

    Output:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: select dealer1_.name as col_0_0_, product0_.name as col_1_0_, sum(product0_.price) as col_2_0_from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id group by product0_.name

    Dealer Name Product Name Price

    Agrawal Computer 23100.0

    Ritu HardDisk 2500.0

  • 8/3/2019 1 Hibernate

    28/36

    Agrawal Keyboard 1500.0

    Ritu Laptop 200.0

    Mohan Mobile 15000.0

    Mohan PenDrive 200.0

    Hibernate Subqueries

    A unidirectional one-to-many association on a foreign key is rarely required.

    A unidirectional one-to-many association on a foreign key is rarely required.

    Here is the hibernate code:

  • 8/3/2019 1 Hibernate

    29/36

    In this example first we create the session object with the help of the SessionFactory interface. Then

    we use the createQuery() method of the Session object which returns a Query object. Now we use

    the openSession() method of the SessionFactory interface simply to instantiate the Session object.

    And the we retrieve the data from the database store it in that Query object and iterate this object

    with the help of Iterator and finally displays the requested data on the console.

    public classSubqueries {

    public static voidmain(String[] args) {// TODO Auto-generated method stubSession sess = null;try{SessionFactory fact = new Configuration().configure().buildSessionFacto

    ry();sess = fact.openSession();String sql_query = "select d.name,p.name,p.price from Product p join p.

    dealer d where p.price in(select p.price from p where p.price > 1500)";Query query = sess.createQuery(sql_query);

    System.out.println("Dealer Name\t"+"Product Name\t"+"Price");for(Iterator it=query.iterate();it.hasNext();){Object[] row = (Object[]) it.next();System.out.print(row[0]);System.out.print("\t\t"+row[1]);System.out.print("\t"+row[2]);System.out.println();

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

    }}

    }

    Output:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

    log4j:WARN Please initialize the log4j system properly.

    Hibernate: select dealer1_.name as col_0_0_, product0_.name as col_1_0_, product0_.price as col_2_0_ fromProduct product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id where product0_.price in (selectproduct0_.price from Product product0_ where product0_.price>1500)

    Dealer Name Product Name Price

    Agrawal Computer 23000.0

    Mohan Mobile 15000.0

    Ritu HardDisk 2500.0

    Hibernate Annotations

    Introduction:- Hibernate needs a metadata to govern the transformation of data from POJO to

  • 8/3/2019 1 Hibernate

    30/36

    database tables and vice versa. Most commonly XML file is used to write the metadata information

    in Hibernate. The Java 5 (Tiger) version has introduced a powerful way to provide the metadata

    to the JVM. The mechanism is known as Annotations. Annotation is the java class which is read

    through reflection mechanism during the runtime by JVM and does the processing accordingly. The

    Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational

    Table mapping. All the metadata is clubbed into the POJO java file along with the code this helpsthe user to understand the table structure and POJO simultaneously during the development. This

    also reduces the management of different files for the metadata and java code.

    Prerequisite for setting the project :-

    1. Make sure you have Java 5.0 or higher version .

    2. You should have Hibernate Core 3.2.0GA and above.

    3. Download and add the Hibernate-Annotations jar file in the project workspace.

    The First Application :-

    Let us assume we have a table Employee which has only two columns i.e ID and Name. In hibernate

    core to achieve the mapping for the above employee table the user should create the following files :-

    1. Utility file for configuring and building the session factory.

    2. Hibernate.cfg.xml or any other Datasource metadata file

    3. Employee POJO object.

    4. employee.hbm.xml file. (This file is now omitted for the )

    5. Real application file which has the actual logic manipulate the POJO

    Note:- Annotations are only the step to remove the hbm.xml file so all the steps remain same only

    some modifications in some part and adding the annotation data for the POJO.

    Please note that coming example will use the Employee table from the database. The SQL query to

    create the employee table is as follows :-

    Create table Employee( ID int2 PRIMARY KEY, NAME nvarchar(30));

    Step 1:- Creating Utility Class :- The following is the code given for the utility class for

    sessionFactory:-

    package net.roseindia;

    import org.hibernate.SessionFactory;

    import org.hibernate.cfg.AnnotationConfiguration;

    public classHibernateUtil {

    private static finalSessionFactory sessionFactory;

    static {

  • 8/3/2019 1 Hibernate

    31/36

    try {

    // Create the SessionFactory from hibernate.cfg.xml

    sessionFactory = new AnnotationConfiguration().configure().buildSession

    Factory();

    } catch (Throwable ex) {

    // Make sure you log the exception, as it might be swallowed

    System.err.println("Initial SessionFactory creation failed." + ex);throw new ExceptionInInitializerError(ex);

    }

    }

    public staticSessionFactory getSessionFactory() {

    return sessionFactory;

    }

    }

    If you see the only change in the file for the annotations is we use AnnotationConfiguration() class

    instead of the Configuratio() class to build the sessionFactory for the hibernate.

    Step 2: - The Hibernate.cfg.xml is the configuration file for the datasource in the Hibernate world.

    The following is the example for the configuration file.

    com.mysql.jdbc.Driverjdbc:mysql://localhost:3306/test

    root

    root

    1

    org.hibernate.dialect.MySQLDialect

    thread

    org.hibernate.cache.NoCacheProvider

    true

    none

  • 8/3/2019 1 Hibernate

    32/36

    The only change is, we are now telling the compiler that instead of any resource get the

    metadata for the mapping from the POJO class itself like in this case it is net.roseindia.Employee .Note:- Using annotations does not mean that you cannot give the hbm.xml file mappng. You can

    mix annotations and hbm.xml files mapping for different Pojo but you cannot mix the mappings for

    the same Pojo in both ways. This we will discuss further.

    Step 3: -The major changes occurred only in the POJO files if you want to use the annotations

    as this is the file which will now contain the mapping of the properties with the database. The

    following is the code for the Employee POJO.

    package net.roseindia;

    import java.io.Serializable;

    import javax.persistence.Column;

    import javax.persistence.Entity;

    import javax.persistence.Id;

    import javax.persistence.Table;

    @Entity

    @Table(name = "employee")

    public classEmployee implements Serializable {

    public Employee() {

    }

    @Id

    @Column(name = "id")

    Integer id;

    @Column(name = "name")

    String name;

    public Integer getId() {

    return id;

    }

    public voidsetId(Integer id) {

    this.id = id;

    }

    public String getName() {

    return name;}

    public voidsetName(String name) {

    this.name = name;

    }

    }

    In the EJB word the entities represent the persistence object. This can be achieved by @Entity at

  • 8/3/2019 1 Hibernate

    33/36

    the class level. @Table(name = "employee") annotation tells the entity is mapped with the table

    employee in the database. Mapped classes must declare the primary key column of the database

    table. Most classes will also have a Java-Beans-style property holding the unique identifier of an

    instance. The @Id element defines the mapping from that property to the primary key column.

    @Column is used to map the entities with the column in the database.

    Step 4: -The following code demonstrate storing the entity in the database. The code is identical as

    you have used in theHibernate applications.

    package net.roseindia;

    import org.hibernate.Session;

    import org.hibernate.SessionFactory;

    import org.hibernate.Transaction;

    public classExample1 {

    public static voidmain(String[] args) throws Exception {

    /** Getting the Session Factory and session */SessionFactory session = HibernateUtil.getSessionFactory();

    Session sess = session.getCurrentSession();

    /** Starting the Transaction */

    Transaction tx = sess.beginTransaction();

    /** Creating Pojo */

    Employee pojo = new Employee();

    pojo.setId(new Integer(5));

    pojo.setName("XYZ");

    /** Saving POJO */

    sess.save(pojo);

    /** Commiting the changes */

    tx.commit();

    System.out.println("Record Inserted");

    /** Closing Session */

    session.close();

    }

    }

    Output :-

    Record Inserted.

    Conclusion:-

    The above article shows the basic configurations for the Hibernate annotations. The above example

    will only add one record in the Database using the hibernate annotations. In the coming article we

    will discuss about the various available annotations in the JPA and the also the examples demonstrate

    how to use the annotations for mapping all the hibernate POJO to the database tables.

  • 8/3/2019 1 Hibernate

    34/36

    Hibernate Caching

    I found some useful information on internet about hibernate caching.I thought of sharing with

    everyone.

    High-volume database traffic is a frequent cause of performance problems in Web applications.

    Hibernate is a high-performance, object/relational persistence and query service. In many cases,second-level caching can be just what Hibernate needs to realize its full performance-handling

    potential.

    What is caching Anything you can do to minimize traffic between a database and an application

    server is probably a good thing. In theory, an application ought to be able to maintain a cache

    containing data already loaded from the database, and only hit the database when information has to

    be updated. When the database is hit, the changes may invalidate the cache.

    There are two different cache used in hibernate-

    1. First Level cache This is associated with session. This is default implemented in hibernate on a

    per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs

    to generate within a given transaction. For example, if an object is modified several times within

    the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of thetransaction, containing all the modifications

    2. Second level cache This is associated with Session Factory object. It will survive Sessions and can

    be reused in new Session by same SessionFactory (which usually is one per application). By default

    the 2nd level cache is not enabled. This second-level cache exists as long as the session factory is

    alive. The second-level cache holds on to the data for all properties and associations for individual

    entities that are marked to be cached. The second level cache is responsible for caching objects across

    sessions.

    Cache Type

    EHCache (Easy Hibernate Cache) http://ehcache.sourceforge.net/

    OSCache (Open Symphony) http://www.opensymphony.com/oscache/

    SwarmCache http://swarmcache.sourceforge.net/JBoss TreeCache http://jboss.org/wiki/Wiki.jsp?page=JBossCache

    EHCache -s an open source widely used java distributed cache for general purpose caching, Java

    EE and light-weight containers. It features memory and disk stores, replicate by copy and invalidate,

    listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter,

    RESTful and SOAP APIs and much more. Ehcache is available under an Apache open source license and

    is actively developed, maintained and supported.It support read only, Non strict Read/write,Read/

    write caching.It does not support transactional caching architecture.

    OSCache is a Java framework developed by OpenSymphony that makes it easy to cache content

    in Web applications.It is a caching solution that includes a JSP tag library and set of classes to perform

    fine grained dynamic caching of JSP content, servlet responses or arbitrary objects.It provides both

    in memory and persistent on disk caches.They can allow your site to have graceful error tolerance .Itsupport read only, Non strict Read/write,Read/write caching.It does not support transactional schema

    caching architecture.

    SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-

    only or nonstrict read/write caching. This type of cache is appropriate for applications that typically

    have many more read operations than write operations.It support read only, Non strict Read/write

    caching.It does not support ,Read/write and transactional caching architecture.It is is a cluster-based

    caching.

  • 8/3/2019 1 Hibernate

    35/36

    JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache.

    Use this solution if you really need a true transaction-capable caching architecture.

    HIBERNATE - Hibernate Mapping In Depth

    Hibernate allows the mapping of Mapped tables with the domain objects using the persistent

    collection-valued fields. These fields needs be declared as an interface type. The actual interface can be

    java.util.Set, java.util.Collection, java.util.List, java.util.Map, java.util.SortedSet, java.util.SortedMap or

    custom implementations of org.hibernate.usertype.UserCollectionType

    Collections instances have the usual behavior of value types. They are automatically persisted when

    referenced by a persistent object and automatically deleted when unreferenced. If a collection is passed

    from one persistent object to another, its elements might be moved from one table to another. Two

    entities may not share a reference to the same collection instance. Due to the underlying relational

    model, collection-valued properties do not support null value semantics;

    public class Product {

    private String serialNumber;

    private Set parts = new HashSet();

    public Set getParts() { return parts; }

    void setParts(Set parts) { this.parts = parts; }

    public String getSerialNumber() { return serialNumber; }

    void setSerialNumber(String sn) { serialNumber = sn; }

    }

    Collection Mapping

    (1)

    (2)

    (3)

    (4)

    (5)

    (6)

    (7)

    (8)

    (9)

    (10)

    (11)

    (12)

    (13)

    (1) name the collection property name

  • 8/3/2019 1 Hibernate

    36/36

    (2) table (optional - defaults to property name) the name of the collection table (not used for one-to-

    many associations)

    (3)schema (optional) the name of a table schema to override the schema declared on the root

    element

    (4) lazy (optional - defaults to true) enable lazy initialization (not available for arrays)

    (5) inverse (optional - defaults to false) mark this collection as the "inverse" end of a bidirectionalassociation

    (6) cascade (optional - defaults to none) enable operations to cascade to child entities

    (7) sort (optional) specify a sorted collection with natural sort order, or a given comparator class

    (8)order-by (optional, JDK1.4 only) specify a table column (or columns) that define the iteration

    order of the Map, Set or bag, together with an optional asc or desc

    (9)where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving or

    removing the collection (useful if the collection should contain only a subset of the available data)

    (10)fetch (optional, defaults to select) Choose between outer-join fetching and fetching by sequential

    select. Only one collection may be fetched by outer join per SQL SELECT.

    (11)batch-size (optional, defaults to 1) specify a "batch size" for lazily fetching instances of this

    collection.

    (12)access (optional - defaults to property): The strategy Hibernate should use for accessing the

    property value.

    (13)

    optimistic-lock (optional - defaults to true): Species that changes to the state of the collection

    results in increment of the owning entity's version. (For one to many associations, it is often

    reasonable to disable this setting.)

    These are some more mapings which we will discuss later

    Association Mapping

    Component MappingInstance Mapping


Recommended