Hibernate

Hibernate
An object model uses the principles of abstraction, encapsulation, modularity, hierarchy, typing,
concurrency, polymorphism, and persistence. The object model enables you to create well-structured, complex systems. In an object model system, objects are the components of the system. Objects are instances of classes, and classes are related to other classes via inheritance relationships. An object has an identity, a state, and behavior. An object model helps you create reusable application frameworks and systems that can evolve over time. In addition, object-oriented systems are usually smaller than non-object-oriented implementations.

A relational model defines the structure of data, data manipulation, and data integrity. Data is
organized in the form of tables, and different tables are associated by means of referential integrity (a foreign key). Integrity constraints such as a primary key, unique check constraints, and not null are used to maintain an entity’s integrity in the relational model.
A relational data model isn’t focused on supporting entity-type inheritance: entity-based
polymorphic association from an object model can’t be translated into similar entities in a relational model. In an object model, you use the state of the model to define equality between objects. But in a relational model, you use an entity’s primary key to define equality of entities. Object references are used to associate different objects in an object model, whereas a foreign key is used to establish associations in a relational model. Object references in the object model facilitate easier navigation through the object graph.

Because these two models are distinctly different, you need a way to persist object entities (Java objects) into a relational database. Figures 1-1 and 1-2 provide a simple representation of the object model and the relational model.

Object/relational mapping (ORM) frameworks help you take advantage of the features present in the object model (like Java) and the relational model (like database management systems [DBMS]). With the help of ORM frameworks, you can persist objects in Java to relational tables using metadata that describes the mapping between the objects and the database. The metadata shields the complexity of dealing directly with SQL and helps you develop solutions in terms of business objects.

An ORM solution can be implemented at various levels:
        Pure relational: An application is designed around the relational model.
        Light object mapping: Entities are represented as classes and are mapped
manually to relational tables.
        Medium object mapping: An application is designed using an object model, and
SQL is generated during build time using code-generation utilities.
        Full object mapping: This mapping supports sophisticated object modeling
including composition, inheritance, polymorphism, and persistence by
reachability.


The following are the benefits of using an ORM framework:

        Productivity: Because you use metadata to persist and query data, development
time decreases and productivity increases.
        Prototyping: Using an ORM framework is extremely useful for quick prototyping.
        Maintainability: Because much of the work is done through configuration, your
code has fewer lines and thus requires less maintenance.
·         Vendor independence: An ORM abstracts an application from the underlying SQL
database and SQL dialect. This gives you the portability to support multiple
databases.

ORM frameworks also have some disadvantages:
        Learning curve: You may experience a steep learning curve as you learn how to
map and, possibly, learn a new query language.
        Overhead: For simple applications that use a single database and data without
many business requirements for complex querying, an ORM framework can be
extra overhead.
        Slower performance: For large batch updates, performance is slower.

Hibernate is one of the most widely used ORM frameworks in the industry. It provides all the
benefits of an ORM solution and implements the Java Persistence API (JPA) defined in the Enterprise JavaBeans (EJB) 3.0 specification.

Its main components are as follows:
        Hibernate Core: The Core generates SQL and relieves you from manually handling
Java Database Connectivity (JDBC) result sets and object conversions. Metadata is
defined in simple XML files. The Core offers various options for writing queries:
plain SQL; Hibernate Query Language (HQL), which is specific to Hibernate;
programmatic criteria, or Query by Example (QBE). It can optimize object loading
with various fetching and caching options.
        Hibernate Annotations: With the introduction of Annotations in JDK 5.0,
Hibernate provides the option of defining metadata using annotations. This
reduces configuration using XML files and makes it simple to define required
metadata directly in the Java source code.
        Hibernate EntityManager: The JPA specification defines programming interfaces,
lifecycle rules for persistent objects, and query features. The Hibernate
implementation for this part of the JPA is available as Hibernate EntityManager
Problems with Using JDBC

Using JDBC means you can execute any kind of SQL statements. For a simple task, you have to code many SELECT, INSERT, UPDATE, and DELETE statements repeatedly. This results in the following issues:

        Too much copy code: When you perform object retrieval, you need to copy the
fields in a ResultSet to the properties of an object. When you perform object
persistence, you need to copy the properties of an object to the parameters in
PreparedStatement.
        Manually handled associations: When you perform object retrieval, you have to
perform a table join or read from several tables to get an object graph. When you
perform object persistence, you must update several tables accordingly.
        Database dependent: The SQL statements you wrote for one database may not
work with another brand of database. Although the chance is very small, you may have to migrate to another database.

Hibernate

It provides powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. The Hibernate Query Language, designed as a "minimal" object-oriented extension to SQL, provides an elegant bridge between the object and relational worlds. Hibernate also allows you to express queries using native SQL or Java-based Criteria and Example queries.
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 permissioned 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 theapplications 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, 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 POJOsinterchangeably.
      
  • The EJB3 draft specification support for POJO persistence and annotations.
Hibernate Architecture




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 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 aSession.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.


Hibernate Architecture: Some Information

o    Lite Architecture: Applications provide their own JDBC connections and also manage their own transactions
o    Full Cream Architecture: Hibernate takes care of the JDBC connections and transaction Management. The applications are relieved of these responsibilities
o    An instance of a persistent class can be in one of three states such as transient, persistent, and detached
o    Hibernate may be managed via a JMX standard service
o    Hibernate may be configured as a JCA connector

Hibernate: Key Points:
o    Open source object/relational mapping tool for Java
o    Provides persistent classes and persistent logic
o    In addition to mapping, provides data query and retrieval facilities
o    Steps: Create a POJO, create an XML mapping file for object to table columns, use Hibernate APIs to load/store the persistent objects
o    hibernate.cfg.xml file keeps properties such as, database connection string and password, database dialect, and mapping files locations
o    Mapping files of the pattern *.hbm keeps mapping between a specific Java class and one or more database tables
Commonly used Hibernate classes:
o    org.hibernate.SessionFactory, org.hibernate.Session, org.hibernate.Transaction
o    A list of Hibernate APIs
o    Class to class mapping can be done using associations. Associations can be one to many, many to one, many to many. (unidirectional and bidirectional)
o    All bi-directional associations need one side as inverse. In an association (bidirectional) the many side needs to be the inverts

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:

Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">admin</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <!-- Mapping files -->
    <mapping resource="book.hbm.xml"/>
    <mapping resource="leave.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Then we need to have a java bean showing all the fields of related table (Developing POJO Class)

public class Book {

    public String isbn;
    public String book_name;
   
    public String getBook_name() {
        return book_name;
    }

    public void setBook_name(String book_name) {
        this.book_name = book_name;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
}


Then a hbm file should be configured:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="hibernatedemo">



 <class name="Book" table="book">
    <id name="isbn" type="string" column="isbn">
      <generator class="assigned"/>
    </id>
    <property name="book_name" type="string" column="book_name"></property>
  </class>
</hibernate-mapping>

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

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

2.      <class> element
The <Class> 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 <hibernate-mapping> element, several <class> mappings are possible.   

3.      <id> element
The <id> element in unique identifier to identify and object. In fact <id> element map with the primary key of the table. In our code : <id name="id" type="long" column="ID" > 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.
    

4.     <generator> element
The <generator> method is 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.    

5.     <property> 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.

Different methods to insert, update, delete, select
public static void insertObject(int state_id,String state_name)
    {
Session  session =sessionFactory.openSession();
            State s=new State();
            //Book b = new Book();
           
            s.setState_id(state_id);
            s.setState_name(state_name);
            session.save(s);
            session.beginTransaction().commit();
            session.close();
    }
    // To Update the Object into Table;
    public static void updateObject(int state_id,String state_name)
    {

            Session  session =sessionFactory.openSession();
            State s=(State)session.get(State.class, state_id);
            s.setState_name(state_name);
            session.merge(s);
            session.beginTransaction().commit();
            session.close();
            System.out.println("Updated!");
    }

    // To Delete the Object into Table;
    public static void deleteObject(int state_id)
    {
            Session  session =sessionFactory.openSession();
            State s=(State)session.get(State.class, state_id);
            session.delete(s);
            session.beginTransaction().commit();
            session.close();
            System.out.println("Deleted!");
    }
    // To Select All Objects from Table;
    public static void selectObject()
    {
            Session  session =sessionFactory.openSession();
            State s=(State)session.get(State.class, 1);
            System.out.println("The --->"+s.getState_name());
            List<Object[]> list=session.createQuery("select s.state_name,s.state_id from State s where s.state_id=4").list();
            session.close();
            for(Object obj[]: list)
            {
                //State s=(State)obj;
                //System.out.println("STATE_ID"+s.getState_id()+"  STATE_NAME "+s.getState_name());
                System.out.println(obj[0]+" "+obj[1]);


            }
    }
Call these methods from BO or main class

static SessionFactory sessionFactory =null;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        try
        {
            sessionFactory = new Configuration().configure().buildSessionFactory();
         
           //z insertObject(6,"Arunachal Pradesh");
            //updateObject(4,"Utter Pradesh");
           //deleteObject(5);
           //selectObject();
   } catch(Exception e)
            {
                System.out.println("Exception:"+e);
            }
    }


Criteria

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 screens, where HQL is not very effective. 
The interface 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:


SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
      session = sessionFactory.openSession();      //Criteria Query Example      Criteria 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();


The above Criteria Query example selects all the records from the table and displays on theconsole. In the above code the following code creates a new Criteria instance, for the classInsurance:
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 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.
uniqueResult
          
This method is used to instruct the Hibernate to fetch and return the unique records 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 set of 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 named property
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 operator
Restriction.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 expressions

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


Criteria 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

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

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");      crit.add(Expression.between("investementDate", new Date(startDate.getTime()), new Date(endDate.getTime()))); //Between date condition      crit.setMaxResults(5); //Restricts the max rows to 5

 

Hibernate Criteria Expression (gt)

Criteria crit = sess.createCriteria(Insurance.class);
      crit.add(Expression.gt("lngInsuranceId",new Long(3)));

 

List list = crit.list();
      for (Iterator it =list.iterator();it.hasNext();){        Insurance ins =(Insurance)it.next();        System.out.println("Insurance Id: "  + ins.getLngInsuranceId());        System.out.println("Insurance Name: " + ins.getInsuranceName());        System.out.println("Insurance Amount: " + ins.getInvestementAmount());        System.out.println("Investement Date: " + ins.getInvestementDate());      }      sess.close();

Hibernate Criteria Expression (and)

Criteria crit = sess.createCriteria(Insurance.class);
      crit.add(Expression.and(Expression.gt("lngInsuranceId",new Long(3)), Expression.lt("lngInsuranceId",new Long(6))));

Hibernate Criteria Expression (or)

Criteria crit = sess.createCriteria(Insurance.class);
      crit.add(Expression.or(Expression.gt("lngInsuranceId",new Long(3)), Expression.lt("lngInsuranceId",new Long(6))));

 


Hibernate Projections
Projections: The package Criteria is used as a framework by the applications just to build the new kinds of projection. may be used by applications as a framework for building new kinds of Projection. In general Projection means to retrieve while in case of SQL Projection means "Select" clause. Most of theapplications uses the built-in projection types by means of the static factory methods of this class.

ProjectionList:  is the list of projection instances which are result of Query's object.
Criteria API:  enables us to specify criteria based on various.
In the class projectionExample.java,  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.
Then we obtain the criteria object simply by invoking the createCriteria() method of the Session's object. Now we create a projectionList object add the fields having properties "name" and "price". Set it to the Criteria object by invoking the setProjection() method and passing the projectList object into this method and then add this object into the List interface's list object and iterate this object list object to display the data contained in this object.

SessionFactory sfact = new Configuration().configure().buildSessionFactory();
      sess = sfact.openSession();
      Criteria crit = sess.createCriteria(Product.class);
      ProjectionList proList = Projections.projectionList();
      proList.add(Projections.property("name"));
      proList.add(Projections.property("price"));
      crit.setProjection(proList);
      List list = crit.list();
      Iterator it = list.iterator();

Hibernate Projections (rowCount or countDistinct)

In this section, you will learn about the hibernate projection with an example. 
Projection Interface: This is an interface that extends the Serializable. An object-oriented representation of a query result set projection in a Criteria query. Built-in projection types are provided by the Projections factory class. The Projection interface might be implemented by application classes that define custom projections.
The following example to count the total number of rows and distinct rows to use theProjections.rowCount() and Projections.countDistinct() method

SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      Criteria crit = sess.createCriteria(Insurance.
class);
      crit.setProjection(Projections.rowCount());
      List result = crit.list();

  System.out.println("No. of rows: "+result);
      crit.setProjection(Projections.distinct(Projections.countDistinct("insuranceName")));
      List distList = crit.list();
      System.out.println("Distinct Count:  "+ distList);

Hibernate Projections (Sum, max, min, avg )

Criteria crit = sess.createCriteria(Insurance.class);
      ProjectionList proList = Projections.projectionList();
      proList.add(Projections.sum("investementAmount"));
      crit.setProjection(proList);
      List sumResult = crit.list();

 


JPA
The Java Persistence Architecture API (JPA) is a Java specification for accessing, persisting, and managing data between Java objects / classes and a relational database. JPA was defined as part of the EJB 3.0 specification as a replacement for the EJB 2 CMP Entity Beans specification. JPA is now considered the standard industry approach for Object to Relational Mapping (ORM) in the Java Industry.
JPA itself is just a specification, not a product; it cannot perform persistence or anything else by itself. JPA is just a set of interfaces, and requires an implementation. There are open-source and commercial JPA implementations to choose from and any Java EE 5 application server should provide support for its use. JPA also requires a database to persist to.
JPA allows POJO (Plain Old Java Objects) to be easily persisted without requiring the classes to implement any interfaces or methods as the EJB 2 CMP specification required. JPA allows an object's object-relational mappings to be defined through standard annotations or XML defining how the Java class maps to a relational database table. JPA also defines a runtime EntityManager API for processing queries and transaction on the objects against the database. JPA defines an object-level query language, JPQL, to allow querying of the objects from the database.

Mapping the identifier property
A regular (noncomposite) identifier property is mapped in Hibernate XML files
with the <id> element:

<class name="Category" table="CATEGORY">
<id name="id" column="CATEGORY_ID" type="long">
<generator class="native"/>
</id>
...
</class>

The identifier property is mapped to the primary key column CATEGORY_ID of the
table CATEGORY. The Hibernate type for this property is long, which maps to a
BIGINT column type in most databases and which has also been chosen to match
the type of the identity value produced by the native identifier generator. (We
discuss identifier generation strategies in the next section.)
For a JPA entity class, you use annotations in the Java source code to map the
identifier property:
@Entity
@Table(name="CATEGORY")
public class Category {
private Long id;
...
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CATEGORY_ID")
public Long getId() {
return this.id;
}
private void setId(Long id) {
this.id = id;
}
...
}

The @Id annotation on the getter method marks it as the identifier property, and
@GeneratedValue with the GenerationType.AUTO option translates into a native
identifier generation strategy, like the native option in XML Hibernate mappings.
Note that if you don’t define a strategy, the default is also GenerationMapping
entities with identity 165
Type.AUTO, so you could have omitted this attribute altogether.

Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns=http://java.sun.com/xml/ns/persistence xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

<persistence-unit name="conn" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
 <class>Address</class>
 <class>Book</class>
 <properties>
<property name = "toplink.jdbc.driver" value = "com.mysql.jdbc.Driver"/>
<property name = "toplink.jdbc.url" value = "jdbc:mysql://localhost:3306/test"/>
<property name = "toplink.jdbc.user" value = "root"/>
<property name = "toplink.jdbc.password" value = "admin"/>
 </properties>       
 </persistence-unit>
 </persistence>

·         <class> :   Define specified java class in it

Java Bean

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author guptavi03
 */
@Entity
@Table(name="address")
@NamedQuery(name="allAddList",query="select a from Address a")
public class Address implements Serializable
{
    @Id
    @GeneratedValue
    @Column(name="address_id")
    private int addID;
    @Column(name="address_street")
    private String addStreet;
    @Column(name="address_city")
    private String addCity;
    @Column(name="address_state")
    private String addState;
    @Column(name="address_zipcode")
    private int addZip;
    public String getAddCity() {
        return addCity;
    }
    public void setAddCity(String addCity) {
        this.addCity = addCity;
    }
    public int getAddID() {
        return addID;
    }
    public void setAddID(int addID) {
        this.addID = addID;
    }
    public String getAddState() {
        return addState;
    }
    public void setAddState(String addState) {
        this.addState = addState;
    }
    public String getAddStreet() {
        return addStreet;
    }
    public void setAddStreet(String addStreet) {
        this.addStreet = addStreet;
    }
    public int getAddZip() {
        return addZip;
    }
    public void setAddZip(int addZip) {
        this.addZip = addZip;
    }
}


Main Class  (INSERT)
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author guptavi03
 */
public class JPATesting {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        EntityManagerFactory emf=Persistence.createEntityManagerFactory("conn");
        System.out.println("EmtityMangerFactory: "+emf);
        EntityManager em=emf.createEntityManager();
        try
        {
            EntityTransaction entr=em.getTransaction();
            entr.begin();
            Address add = new Address();
            add.setAddID(4);
            add.setAddStreet("N");
            add.setAddCity("delhi");
            add.setAddState("delhi");
            add.setAddZip(110018);
            em.persist(add);
            entr.commit();
        }
        catch(Exception e)
        {
            System.out.println("exception"+e.getMessage());
        }
       
READ DATA
List<Address> addList=em.createQuery("select a from Address a where a.addCity=:cityName").             setParameter("cityName", "Delhi").getResultList();
        List<Address> addList=em.createNamedQuery("allAddList").getResultList();  
        for(Address add:addList)
        {
            System.out.println("Add_id:"+add.getAddID());
            System.out.print("  Add_CIty:"+add.getAddCity());
            System.out.print("  Add_State"+add.getAddState());
            System.out.print("  Add_Street:"+add.getAddStreet());
            System.out.print("  Add_Zipcode:"+add.getAddZip());
        }

        Address addObj=em.find(Address.class, 1);
        System.out.println("Add_id:"+addObj.getAddID());
        System.out.print("  Add_CIty:"+addObj.getAddCity());
        System.out.print("  Add_State"+addObj.getAddState());
        System.out.print("  Add_Street:"+addObj.getAddStreet());
        System.out.print("  Add_Zipcode:"+addObj.getAddZip());


Update
      EntityTransaction entr = em.getTransaction();
      entr.begin();
      Employee emp = em.find(Employee.class, 1);
      emp.setEmpName("Suresh Prasad");
      emp.setEmpSalary(35000);
      entr.commit();

Delete
Employee emp = em.find(Employee.class, 1);
em.remove(emp);
entr.commit();

GetResultList Function

ThegetResultList() function to use for getting the records form databse as a list.
This funcation invokes with Query object. The getResultList function always returs a list. This list return eithor one or more records.
List<Address> addList = em.createQuery("select a from Address a").getResultList();
            for(Address a:addList)
            {  System.out.println(""+a.getAddCity());
               System.out.println(""+a.getAddState());
            }
             entr.commit();

GetSingleResult Function

The getSingleResult() function to use for getting single record form databse.
The getSingleResult() funcation invokes with Query object. It returns only single records any times.

 

Query q = em.createQuery("select a from Address a where a.addID =:id").setParameter("id", 1);

Address add = (Address)q.getSingleResult();

System.out.println(""+add.getAddCity());

System.out.println(""+add.getAddState());

System.out.println(""+add.getAddStreet());

System.out.println(""+add.getAddZip());

entr.commit();

 

One-to-Many Relationship

In this relationship each record in Table-A may have many related records in Table-B, but each record inTable-B may have only one corresponding record in Table-A.
Here, we are going to describe the one-to-many relation. The@OneToMany annotation to provide the one-to-many relation. There are three tables: parent, child and parentchild. One parent has many children. The parent and child tables are integrated with the parentchild table through the files: parentId and childrenId. In the parentchild table, the one parentId has different childrenId.
http://www.roseindia.net/jpa/eclipsejpaexamples/jparelationship/oneto-many.gif
  • parent
CREATE TABLE `parent` (
`id` int(11) NOT NULL auto_increment,
`pname` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
);
  • child
CREATE TABLE `child` (
`id` int(11) NOT NULL auto_increment,
`cname` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
);
  • parentchild
CREATE TABLE `parentchild` (
`parentId` int(11) NOT NULL default '0',
`childrenId` int(11) NOT NULL,
PRIMARY KEY (`parentId`,`childrenId`),
UNIQUE KEY `childrenId` (`childrenId`),
KEY `FK9E5C7E72A1A8B75` (`parentId`),
KEY `FK9E5C7E725FABE430` (`childrenId`),
CONSTRAINT `FK9E5C7E725FABE430` FOREIGN KEY (`childrenId`) REFERENCES `child` (`id`),
CONSTRAINT `FK9E5C7E72A1A8B75` FOREIGN KEY (`parentId`) REFERENCES `parent` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

 

Parent.java

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package jpa;

import java.io.Serializable;

import java.util.List;

import java.util.Set;

import javax.persistence.Basic;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.JoinTable;

import javax.persistence.ManyToOne;

import javax.persistence.OneToMany;

import javax.persistence.Table;

/**

 *

 * @author guptavi03 */

@Entity

@Table(name = "parent")

public class Parent implements Serializable {

    @Id

    @GeneratedValue  

    @Column(name = "parent_id")

    private Integer parentId;

    @Column(name = "pname")

    private String pname;

   /**

     * mappedBY = (parent is column name(foreign key) in child table i.e Child)

     * private List<Child> children;     Child table

     */

     @OneToMany(cascade=CascadeType.ALL,mappedBy="parent",fetch=FetchType.LAZY)

    private List<Child> children;

    public Parent() {

    }

    public Parent(Integer parentId) {

        this.parentId = parentId;

    }

    public Integer getParentId() {

        return parentId;

    }

    public void setParentId(Integer parentId) {

        this.parentId = parentId;

    }

    public String getPname() {

        return pname;

    }

    public void setPname(String pname) {

        this.pname = pname;

    }

    public List<Child> getChildren() {

        return children;

    }

    public void setChildren(List<Child> children) {

        this.children = children;

    }

}

Child.java

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package jpa;

import java.io.Serializable;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.JoinTable;

import javax.persistence.ManyToOne;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

/**

 *

 * @author guptavi03

 */

@Entity

@Table(name = "child")

public class Child implements Serializable {  

    @Id

    @GeneratedValue   

    @Column(name = "child_id")

    private Integer childId;

    @Column(name = "cname")

    private String cname;

 

    /**

     * JoinColumn (name="parent")   is column name which is a foreign key

     */

    @ManyToOne

    @JoinColumn(name="parent")

    private Parent parent;

    public Child() {

    }

 

    public Child(Integer childId) {

        this.childId = childId;

    }

    public Integer getChildId() {

        return childId;

    }

    public void setChildId(Integer childId) {

        this.childId = childId;

    }

    public String getCname() {

        return cname;

    }

    public void setCname(String cname) {

        this.cname = cname;

    }

    public Parent getParent() {

        return parent;

    }

    public void setParent(Parent parent) {

        this.parent = parent;

    }

}

 

Main.java

           EntityTransaction ent = em.getTransaction();

            ent.begin();

            Parent p = new Parent();

            p.setPname("Saurabh");

            em.persist(p);

            Child c = new Child();

            c.setCname("v1");

            c.setParent(p);

            em.persist(c);

            ent.commit();

 

 

 



One-to-One Relationship

 In the one-to-one relation mapping a single value association to another entity. 
One-to-One: In one-to-one relation, there is one record inTable-A that corresponds to exactly one record in Table-B.
n this relationship, the Address is defined with a one-to-one relationship with annotating the person property in the Address class. The JoinColumn information is also defined. The name attribute defines the foreign key on the table to which the Address class is mapped, and the referenced column defines the primary key to which the Table Person is mapped. Any constraints on the relationship are defined as an attribute to the @OneToOne annotation.
There are two tables: person and address. Both are related to each other through the one-to-one relation. The each person has only one address in this example. Each person has unique id that is referenced to another table address. 

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:

Example:
Steps1: create  hibernate.cfg.xml.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/demo</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"/>
    <property name="hibernate.connection.pool_size">5</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping resource="contact.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


Steps2: create  contact.java
package com.bean;
public class contact {

  private String firstname;
  private String lastname;
  private String email;
  private long id;

    /**
     * @return the firstname
     */
    public String getFirstname() {
        return firstname;
    }

    /**
     * @param firstname the firstname to set
     */
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    /**
     * @return the lastname
     */
    public String getLastname() {
        return lastname;
    }

    /**
     * @param lastname the lastname to set
     */
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the id
     */
    public long  getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = 1;
    }

    /**
     * @return the firstName
     */
   
}
Steps3: create  contact.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.bean.contact" table="contact">
    <id column="id" name="id" type="long">
      <generator class="assigned"/>
    </id>
    <property name="firstname">
      <column name="firstname"/>
    </property>
    <property name="lastname">
      <column name="lastname"/>
    </property>
    <property name="email">
      <column name="email"/>
    </property>
  </class>
</hibernate-mapping>
Steps3: create  FirstSess.java
package com.session;

import com.bean.contact;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author devrat.upadhyay
 */
public class FirstSess {

    public static void main(String ar[]) {
        Session session = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();

            System.out.println("Inserting Record");
            contact contact = new contact();
            contact.setId(1l);
            contact.setFirstname("Rahul");
            contact.setLastname("Kumar");
            contact.setEmail("rahul@yahoo.com");
             session.save(contact);
          session.getTransaction().commit();
        
            System.out.println("Done");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            // Actual contact insertion will happen at this step
            session.flush();
            session.close();

        }
    }
}

Update a Record in Database:         You have to makes change in on record.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.session;

import com.bean.contact;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author devrat.upadhyay
 */
public class updateDemo {

    public static void main(String ar[]) {
        Session session = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();

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

            contact fn = (contact) session.get(contact.class, new Long(1));
            fn.setFirstname("Ravi");
            fn.setLastname("Verma");
            fn.setEmail("ravi@yahoo.com");
            session.update(fn);
            session.getTransaction().commit();

            System.out.println("Updated Successfully");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            // Actual contact insertion will happen at this step
            session.flush();
            session.close();

        }
    }
}




    FlushMode:
You can override the default flushing behavior of the Hibernate Session if you so desire. To have more control over how and when Hibernate will flush the changes that the Session is marinating, you can set the Session's FlushMode. There are five flush modes, although one has been deprecated. They are:
·AUTO - the Session is typically flushed before query execution to ensure query results do not contain stale data
·ALWAYS - the Session is flushed before every query
·COMMIT - the Session is flushed when the transaction.commit() method is called
·MANUAL - the Session is only flushed when the flush() method is invoked on the Session
· 
                              The opposite of flush()? refresh()?
public void refresh(Object object) throws HibernateException
Parameters: object -a persistent or detached instance
Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement long-running sessions that span many business tasks.
This method is, however, useful in certain special circumstances:
-- where a database trigger alters the object state upon insert or update
-- after executing direct SQL (eg. a mass update) in the same session
-- after inserting a Blob or Clob

Hibernate Lifecycle:
Hibernate considers objects it can manage to always be in one of four states
·Transient
·Persistent
·Removed
·Detached

Transient State
All objects start off in the transient state Account account = new Account();   account account is a transient object is a transient object. Hibernate is not aware of the object instance. Not related to database row. No value for accounted. Garbage collected when no longer referenced by any other objects.

Persistent State
Hibernate is aware of, and managing, the object has a database id – Already existing object retrieved from the database. –Formerly transient object about to be saved.
This is the only state where objects are saved to the database.– Modifications made in other states are NOT saved to the database while the object remains in that state. – Changes to objects in a persistent state are automatically saved to the database without invoking session persistence methods. Objects are made persistent through calls against the Hibernate session– session.save(account); – session.lock(account);– session.update(account); – session.merge(account);
Session session = SessionFactory.getCurrentSession(); //transient state Hibernate is NOT aware that it exists
Account account   = new Account();// transition to the ‘persistent’ state. Hibernate is NOW
// aware of the object and will save it to the database
session.saveOrUpdate(account);// modification of the obj y ject will automatically be saved because the object is in the ‘persistent’ state/
account.setBalance(500);
 session.getTransaction().commit();  // commit the transaction

Removed State
A previously persistent object that is deleted from the database – session.delete(account);. Java instance may still exist, but it is ignored by Hibernate. Any changes made to the object are not saved to the database. Picked up for garbage collection once it falls out of scope. Hibernate does not null out the in the in- memory object.
Session session = SessionFactory.getCurrentSession();
// retrieve account with id 1.  account is returned in a ‘persistent’ state
Account account  = session.get(Account.class, 1);
//// transition to the ‘removed’ state Hibernate deletes the transition to the ‘removed’ state. Hibernate deletes the
// database record, and no longer manages the object
session.delete(account);
//// f modification is ignored by Hibernate since it is in the ‘removed’ state
account.setBalance(500);
// commit the transaction
session.getTransaction().commit(); 
// notice the Java object is still alive, though deleted from the database.
//// stays alive until developer sets to null, or goes out of scope stays alive until developer sets to null, or goes out of scope
account.setBalance(1000);

Detached State
A persistent object that is still referenced after closure closure of the active session of the active session.
– session.close() changes object’s state from persisted to detached.
Still represents a valid row in the database. No longer managed by Hibernate
– Changes made to detached objects are not saved to the  database while object remains in the detached state.
–Can be reattached, returning it to the persistent state and causing it to save its state to the database.
update();
 merge();
 lock(); // reattaches, but does not save state


Hibernate Lifecycle






Remember: Once submitted, modifications to the database are not permanent permanent until a commit is issued until a commit is issued session.getTransaction().commit();

Persistence Context
Managed object environment no API or concrete object to reference, just conceptual Thought of as containing:
• Graph of managed persistent instances .
• List List of SQL statements to send to the database of SQL statements to send to the database.
• Each Hibernate session is said to have one ‘persistence context.

Session API –Object Object Persistence Persistence
• session.save(Object o) – Schedules insert statements to create the new object in the database
• session.update(Object o) – Schedules update statements to modify the existing object in the database.
• session.saveOrUpdate(Object o) – Convenience method to determine if a ‘save’ or ‘update’ is required
• session.merge(Object o) – Retrieves a fresh version of the object from the database and based on that, as well as modifications made to the object being passed in, schedules update statements to modify the existing object in the database.
• session.get(Object.class, Identifier) – Retrieves an object instance, or null if not found
• session.load(Object.class, Identifier) – Retrieves an object instance but does NOT result in a database call
• If managed instance not found, will return a proxy– Object fully initialized when non-id attribute is accessed . If ‘detached’, throws ObjectNotFoundExceptionSession API –

Object Object Retrieval Retrieval
• session.lock(Object, LockMode) – Reattaches a detached object to a session without scheduling an update
–Also used to ‘lock’records in the database in the database
• session.refresh(Object) – Gets the latest version from the database .

Session API –Other Other Methods Methods
• session.delete(Object) – Schedule an object for removal from the database.
• session.evict(Object) – Removes individual instances from persistence context, changing their state from persistent to detached.
• session.clear() – Removes all objects from persistence context, changing all their states from persistent to detached
• session.replicate(Object, ReplicationMode)– Used for persisting records across databases
– ReplicationModes
• EXCEPTION: throw exception if row exists
• IGNORE:don ‘t create if already exists create if already exists
• LATEST_VERSION: choose the latest version to save
• OVERWRITE: overwrite existing row

Hibernate 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. 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.
other options to used Hibernate:
1.      Query By Criteria (QBC)
2.      Query BY Example (QBE)   //Criteria API
3.      Native SQL

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 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
Query
1.      From Query
package com.session;
import com.bean.contact;
import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/** * * @author devrat.upadhyay */
public class select {
    public static void main(String ar[]) {
        Session session = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Transaction tr = session.beginTransaction();
            String hql = "from contact ";
            Query q = session.createQuery(hql);
             tr.commit();
            for (Iterator it = q.iterate(); it.hasNext();) {
             contact c = (contact) it.next();
                System.out.println("ID: " + c.getId());
                System.out.println("FirstName: " + c.getFirstname());
                System.out.println("lastName: " + c.getLastname());
                System.out.println("Successfully done");
            }
            session.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
        }
    }
}

2.  Select Query

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.session;


import com.bean.contact;
import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


/**
 *
 * @author devrat.upadhyay
 */
public class select {


    public static void main(String ar[]) {
        Session session = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Transaction tr = session.beginTransaction();


           //String hql ="Select contact.firstname from  contact contact";
            String hql ="Select contact.firstname,contact.lastname,contact.email,contact.id from  contact contact";
            Query q = session.createQuery(hql);
                        tr.commit();
            for (Iterator it = q.iterate(); it.hasNext();) {
               Object[] row = (Object[]) it.next();
               // String row = it.next().toString();


                System.out.println("ID: " + row[3]);
                System.out.println("FirstName: " + row[0]);
                System.out.println("lastName: " + row[1]);
                System.out.println("lastName: " + row[2]);
                System.out.println("Successfully done");
            }


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


    }
}



3.  Where Clause

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.session;


import com.bean.contact;
import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


/**
 *
 * @author devrat.upadhyay
 */
public class where {


    public static void main(String ar[]) {
        Session session = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Transaction tr = session.beginTransaction();


            String hql = "from contact as contact where contact.id='1' ";
            Query q = session.createQuery(hql);
            tr.commit();
            for (Iterator it = q.iterate(); it.hasNext();) {
                contact c = (contact) it.next();
                System.out.println("ID: " + c.getId());
                System.out.println("FirstName: " + c.getFirstname());
                System.out.println("lastName: " + c.getLastname());
                System.out.println("Successfully done");
            }


            System.out.println("**************** ***************");
            System.out.println("Where Clause With Select Clause");
            //Where Clause With Select Clause
            String sql ="select contact.firstname,contact.lastname,contact.email from contact contact where contact.id='1'";


            Query query = session.createQuery(sql);
        
            for (Iterator it = query.iterate(); it.hasNext();) {
                Object[] row = (Object[]) it.next();
                System.out.println("ID: " + row[3]);
                System.out.println("FirstName: " + row[0]);
                System.out.println("LastName: " + row[1]);
                System.out.println("Emailid: " + row[2]);
                
            }


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


    }
}

4.      Delete
package com.session;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Delete {
    /*

    /**
     *
     * @author devrat.upadhyay
     */

    public static void main(String ar[]) {
        Session session = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Transaction tr = session.beginTransaction();
           
            String hql = "delete from contact where firstname = :firstname";
            Query q = session.createQuery(hql);
            q.setParameter("firstname","Raj");
            int row = q.executeUpdate();
            tr.commit();
            if (row == 1) {
                System.out.println("Deleted Row:" + row);
            } else {
               System.out.println("Does not deleted any row !");
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            // Actual contact insertion will happen at this step
            session.flush();
            session.close();

        }
    }
}

5.      Update Query
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.session;

import com.bean.contact;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author devrat.upadhyay
 */
public class updateDemo {

    public static void main(String ar[]) {
        Session session = null;
        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();

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

            contact fn = (contact) session.get(contact.class, new Long(3));
            fn.setFirstname("Renu1");
            fn.setLastname("jha1");
            fn.setEmail("renu@yahoo.com");
            session.update(fn);
            session.getTransaction().commit();

            System.out.println("Updated Successfully");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            // Actual contact insertion will happen at this step
            session.flush();
            session.close();

        }
    }
}

6.      Order By
String SQL_QUERY = "from Insurance as insurance order by contact.name”;
  Query query = session.createQuery(SQL_QUERY);
  for (Iterator it = query.iterate(); it.hasNext();) {
  contact ins = (contact) it.next();

7.       Group By
String SQL_QUERY= "select sum(insurance.investementAmount),insurance.insuranceName from Insurance insurance group by insurance.insuranceName";
 Query query = session.createQuery(SQL_QUERY);
 for (Iterator it =query.iterate(); it.hasNext();) {
 Object[] row = (Object[]) it.next();
System.out.println("Invested Amount: " + row[0]);
System.out.println("Insurance Name: " + row[1]);


8.       Aggregate functions are:
String SQL_QUERY = "select avg(Marks) from student student";
Query query = sess.createQuery(SQL_QUERY);
List list = query.list();
System.out.println("Average of Marks: " + list.get(0));

Only SQL_QUERY Value is changed-
String SQL_QUERY = "select max(Marks)from Student";

9.       Count
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)

10.  Avg
String SQL_QUERY = "select avg(Marks) from student student";



Struts Hibernate Integration
1.welcomeStruts.jsp


<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>


<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>


<html:html locale="true">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title><bean:message key="welcome.title"/></title>
        <html:base/>
    </head>
    <body style="background-color: white">
        
        <logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application">
            <div  style="color: red">
                ERROR:  Application resources not loaded -- check servlet container
                logs for error messages.
            </div>
        </logic:notPresent>
        
        <h3><bean:message key="welcome.heading"/></h3>
        <p><bean:message key="welcome.message"/></p>


        <html:form action="/addcoustom">
            Username<html:text property="firstname" value=""/><br/>
             lastname<html:text property="lastname" value=""/><br/>
              email<html:text property="email" value=""/><br/>


            <html:submit value="GO"/>
        </html:form>
        
    </body>
</html:html>


2. Struts-config.xml



<?xml version="1.0" encoding="UTF-8" ?>


<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">




<struts-config>
    <form-beans>
        <form-bean name="mployeebean" type="com.act.mployeebean"/>
    
    </form-beans>
    
    <global-exceptions>
    
    </global-exceptions>


    <global-forwards>
        <forward name="welcome"  path="/Welcome.do"/>
    </global-forwards>


    <action-mappings>
        <action path="/addcoustom" type="com.act.AddCustomerAction"  name="mployeebean" scope="session" parameter="" validate="false">
            <forward name="success" path="/success.jsp"/>
            <forward name="fail" path="/failure.jsp"/>
         </action>


        <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>
    
    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>


    <message-resources parameter="com/myapp/struts/ApplicationResource"/>
  
    
    <!-- ========================= Tiles plugin ===============================-->
    <!--
    This plugin initialize Tiles definition factory. This later can takes some
    parameters explained here after. The plugin first read parameters from
    web.xml, thenoverload them with parameters defined here. All parameters
    are optional.
    The plugin should be declared in each struts-config file.
    - definitions-config: (optional)
    Specify configuration file names. There can be several comma
    separated file names (default: ?? )
    - moduleAware: (optional - struts1.1)
    Specify if the Tiles definition factory is module aware. If true
    (default), there will be one factory for each Struts module.
    If false, there will be one common factory for all module. In this
    later case, it is still needed to declare one plugin per module.
    The factory will be initialized with parameters found in the first
    initialized plugin (generally the one associated with the default
    module).
    true : One factory per module. (default)
    false : one single shared factory for all modules
    - definitions-parser-validate: (optional)
    Specify if xml parser should validate the Tiles configuration file.
    true : validate. DTD should be specified in file header (default)
    false : no validation


    Paths found in Tiles definitions are relative to the main context.
    -->
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />      
        <set-property property="moduleAware" value="true" />
    </plug-in>
    
    <!-- ========================= Validator plugin ================================= -->
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property  property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
    </plug-in>


    <plug-in className="com.plug.HibernatePlugin">
        <set-property property="path" value="com/plug/HibernatePlugin.java"/>
    </plug-in>




</struts-config>


3. Struts Hibernate integration plugin( make a class : HibernatePlugin)



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.plug;


/**
 *
 * @author devrat.upadhyay
 */
import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;


public class HibernatePlugin implements PlugIn {


    private String _configFilePath = "/hibernate.cfg.xml";
    /**
     * the key under which the <code>SessionFactory </code> instance is stored
     * in the <code>ServletContext</code>.
     */
    public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName();
    private SessionFactory _factory = null;


    public void destroy() {
        try {
            _factory.close();
        } catch (HibernateException e) {
            System.out.println("Unable to close Hibernate Session Factory: " + e.getMessage());
        }


    }


    public void init(ActionServlet servlet,ModuleConfig config) throws ServletException {
        System.out.println("*************************************");
        System.out.println("**** Initilizing HibernatePlugIn **********");
        Configuration configuration = null;
        URL configFileURL = null;
        ServletContext context = null;


        try {


            configFileURL =HibernatePlugin.class.getResource(_configFilePath);
            //configFileURL =HibernatePlugin.class.getResource("org.hibrenate.SessionFactory");


            System.out.println("*******"+configFileURL);


            context = servlet.getServletContext();
            configuration = (new Configuration()).configure(configFileURL);
            System.out.println("*******"+configuration);


            _factory = configuration.buildSessionFactory();
            System.out.println("*******"+_factory);
            //Set the factory into session
            context.setAttribute(SESSION_FACTORY_KEY, _factory);


        } catch (HibernateException e) {
            System.out.println("Error while initializing hibernate: " + e.getMessage());
        }
        System.out.println("**************** *********************");


    }


    /**
     * Setter for property configFilePath.
     * @param configFilePath New value of property configFilePath.
     */
    public void setConfigFilePath(String configFilePath) {
        if ((configFilePath == null) || (configFilePath.trim().length() == 0)) {
            throw new IllegalArgumentException("configFilePath cannot be blank or null.");
        }


        System.out.println("Setting ' configFilePath' to '" + configFilePath + "'...");
        _configFilePath = configFilePath;
    }


    public static void main(String ar[]){
    HibernatePlugin h=new HibernatePlugin();
    
    h.setConfigFilePath(SESSION_FACTORY_KEY);
    }
}



4.hibernate.cfg.xml(in a default package)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/demo</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.pool_size">5</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping resource="contact.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


5.contact.hdm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.act.contact" table="contact">
    <id column="id" name="id" type="long">
      <generator class="increment"/>
    </id>
    <property name="firstname">
      <column name="firstname"/>
    </property>
    <property name="lastname">
      <column name="lastname"/>
    </property>
    <property name="email">
      <column name="email"/>
    </property>
  </class>
</hibernate-mapping>

6.mployeebean.java(Struts Actionform)
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.act;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author devrat.upadhyay
 */
public class mployeebean extends org.apache.struts.action.ActionForm {
    
    private String name;
    private String firstname,lastname,email;

    private int number;
    private long  id;

    /**
     * @return
     */
    public String getName() {
        return name;
    }

    /**
     * @param string
     */
    public void setName(String string) {
        name = string;
    }

    /**
     * @return
     */
    public int getNumber() {
        return number;
    }

    /**
     * @param i
     */
    public void setNumber(int i) {
        number = i;
    }

    /**
     *
     */
    public mployeebean() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param request The HTTP Request we are processing.
     * @return
     */
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (getName() == null || getName().length() < 1) {
            errors.add("name", new ActionMessage("error.name.required"));
            // TODO: add 'error.name.required' key to your resources
        }
        return errors;
    }

    /**
     * @return the firstname
     */
    public String getFirstname() {
        return firstname;
    }

    /**
     * @param firstname the firstname to set
     */
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    /**
     * @return the lastname
     */
    public String getLastname() {
        return lastname;
    }

    /**
     * @param lastname the lastname to set
     */
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the id
     */
    public long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(long id) {
        this.id = id;
    }

    /**
     * @return the id
     */
    
}

7. contact.java(normal java class for Database interaction)
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.act;

/**
 *
 * @author devrat.upadhyay
 */
public class contact {

    private String name;
    private String firstname,  lastname,  email;
    private int number;
    private long  id;

    /**
     * @return
     */
    public String getName() {
        return name;
    }

    /**
     * @param string
     */
    public void setName(String string) {
        name = string;
    }

    /**
     * @return
     */
    public int getNumber() {
        return number;
    }

    /**
     * @param i
     */
    public void setNumber(int i) {
        number = i;
    }

    public String getFirstname() {
        return firstname;
    }

    /**
     * @param firstname the firstname to set
     */
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    /**
     * @return the lastname
     */
    public String getLastname() {
        return lastname;
    }

    /**
     * @param lastname the lastname to set
     */
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the id
     */
    public long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(long id) {
        this.id = id;
    }

    /**
     * @return the id
     */
    
}