Archive for the ‘Hibernate’ Category

hibernate filters

Posted: June 19, 2012 in Hibernate

A filter in the HB provides environment to pass conditions of the persistent logic from outside the java sources through HB mapping file. A HB filter is a global, named, parameterized filter representing conditions like where clause. Having the ability of enabling or disabling them for a particular Hibernate Session.

Working with filters is nothing but making the conditions of the queries coming to application through hibernate mapping file.

Filters of hibernate are introduced from Hibernate 3.x version.

Steps to work with HB Filters to filter the data through the restrictions:

1)Define filter having parameters in Hibernate mapping file

<hibernate-mapping>

<class>

……

……

</class>

<filter-def name=”myfilter”>

<filter-param name=”myid1″ type=”integer”/>

<filter-param name=”myid2″ type=”integer”/>

</filter-def>

</hibernate-mapping>

2)link/configure filter with Hibernate pojo class through the Hibernate mapping file.

<hibernate-mapping>

<class>

……

……

<filter name=”myfilter” condition=”vendorid >= :myid1 and vendorid &lt;= :myid2″></filter>

</class>

<filter-def name=”myfilter”>

<filter-param name=”myid1″ type=”integer”/>

<filter-param name=”myid2″ type=”integer”/>

</filter-def>

</hibernate-mapping>

3)Enable filter on Hibernate Session Object and supplies values for filter parameters.

Filter filter = session.enableFilter(“myfilter”);

filter.setParameter(“myid1”,new Integer(3));

filter.setParameter(“myid2”,new Integer(5));

following resources are needed .

I) vendormaster table

CREATE TABLE `vendormaster` (
`vendorid` int(20) NOT NULL AUTO_INCREMENT,
`vendorname` varchar(50) DEFAULT NULL,
`vendoraddress` varchar(500) NOT NULL,
`vendorphone` varchar(20) NOT NULL,
`vendoremail` varchar(50) DEFAULT NULL,
PRIMARY KEY (`vendorid`)
)

Table having following records:

vid  name      address                        phone                        email

2       aaaa       sivalayam streets    9030211179               prem@gmail.com
3       bbbb      street                           9089786645              ppprr@gmail.com
4      cccc        cstreet                        9030211179               cccc@gmail.com
5      dddd       dstreet                        986624636               gopi.reshu@gmail.com

2) Vendormaster.java (pojo class)

public class Vendormaster implements java.io.Serializable {

private Integer vendorid;
private String vendorname;
private String vendoraddress;
private String vendorphone;
private String vendoremail;

public Vendormaster() {
}

public Vendormaster(String vendoraddress, String vendorphone) {
this.vendoraddress = vendoraddress;
this.vendorphone = vendorphone;
}

public Vendormaster(String vendorname, String vendoraddress,
String vendorphone, String vendoremail) {
this.vendorname = vendorname;
this.vendoraddress = vendoraddress;
this.vendorphone = vendorphone;
this.vendoremail = vendoremail;

}

public Integer getVendorid() {
return this.vendorid;
}

public void setVendorid(Integer vendorid) {
this.vendorid = vendorid;
}

public String getVendorname() {
return this.vendorname;
}

public void setVendorname(String vendorname) {
this.vendorname = vendorname;
}

public String getVendoraddress() {
return this.vendoraddress;
}

public void setVendoraddress(String vendoraddress) {
this.vendoraddress = vendoraddress;
}

public String getVendorphone() {
return this.vendorphone;
}

public void setVendorphone(String vendorphone) {
this.vendorphone = vendorphone;
}

public String getVendoremail() {
return this.vendoremail;
}

public void setVendoremail(String vendoremail) {
this.vendoremail = vendoremail;
}

}

3) Vendormaster.hbm.xml

<hibernate-mapping>
<class name=”com.shal.model.Vendormaster” table=”vendormaster” catalog=”cismysqldb”>
<id name=”vendorid” type=”java.lang.Integer”>
<column name=”vendorid” />
<generator class=”identity” />
</id>
<property name=”vendorname” type=”string”>
<column name=”vendorname” length=”50″ />
</property>
<property name=”vendoraddress” type=”string”>
<column name=”vendoraddress” length=”500″ not-null=”true” />
</property>
<property name=”vendorphone” type=”string”>
<column name=”vendorphone” length=”20″ not-null=”true” />
</property>
<property name=”vendoremail” type=”string”>
<column name=”vendoremail” length=”50″ />
</property>
<filter name=”myfilter” condition=”vendorid >= :myid1 and vendorid &lt;= :myid2″></filter>
</class>
<filter-def name=”myfilter”>
<filter-param name=”myid1″ type=”integer”/>
<filter-param name=”myid2″ type=”integer”/>
</filter-def>
</hibernate-mapping>

4)hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
<property name=”connection.useUnicode”>true</property>
<property name=”connection.characterEncoding”>UTF-8</property>
<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”connection.url”>jdbc:mysql://localhost/test</property>
<property name=”connection.username”>gopal</property>
<property name=”connection.password”>gopal</property>
<property name=”show_sql”>false</property>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”current_session_context_class”>thread</property>
<property name=”hibernate.transaction.factory_class”>org.hibernate.transaction.JDBCTransactionFactory</property>
<mapping resource=”com/shal/model/Vendormaster.hbm.xml”/>
</session-factory>
</hibernate-configuration>

5) HibernateUtil.java (for Session —–> Singleton class) 

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory()
{
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println(“Initial SessionFactory creation failed.” + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

6) Mymain.java

public class Mymain {
public static void main(String[] args)throws Exception {

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction().begin();
Filter filter = session.enableFilter(“myfilter”);
filter.setParameter(“myid1”,new Integer(3));
filter.setParameter(“myid2”,new Integer(5));
try
{
Query query = session.createQuery(“from Vendormaster”);
List list = query.list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
Vendormaster vendormaster = (Vendormaster) iterator.next();
System.out.println(“Vendor Id is “+vendormaster.getVendorid());
}

}catch(Exception e){
e.printStackTrace();
}
session.disableFilter(“myfilter”);
System.out.println(“\n\n”);
System.out.println(“\n\n”);

try
{
Query query = session.createQuery(“from Vendormaster”);
List list = query.list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
Vendormaster vendormaster = (Vendormaster) iterator.next();
System.out.println(“Vendor Id is “+vendormaster.getVendorid());
}

}catch(Exception e){
e.printStackTrace();
}
}

}

 

Output:

Vendor Id is 3
Vendor Id is 4
Vendor Id is 5

 

 
Vendor Id is 2
Vendor Id is 3
Vendor Id is 4
Vendor Id is 5

Hibernate Interceptors

Posted: June 19, 2012 in Hibernate

We know about interceptors are available in frameworks like strus2, spring. Even Hibernate ORM tool also having this kind of feature. Interceptor means request processing life cycle. Interceptors will be invoked based on the requirement like before saving a record into table, updating record, deleting a record and so..on.

In Hibernate I have gone through the EmptyInterceptor  class. It doesn’t have any methods we ourselves configure the methods like below.

1 findDirty()
This method is be called when the flush() method is called on a Session object.
2 instantiate()
This method is called when a persisted class is instantiated.
3 isUnsaved()
This method is called when an object is passed to the saveOrUpdate() method/
4 onDelete()
This method is called before an object is deleted.
5 onFlushDirty()
This method is called when Hibernate detects that an object is dirty (ie. have been changed) during a flush i.e. update operation.
6 onLoad()
This method is called before an object is initialized.
7 onSave()
This method is called before an object is saved.
8 postFlush()
This method is called after a flush has occurred and an object has been updated in memory.
9 preFlush()
This method is called before a flush.

Let see our application developed using hibernateinterceptor concept and following files are needed.

  1. Usermaster (table)
  2. Usermaster.java
  3. Usermaster.hbm.xml
  4. Hibernate.cfg.xml
  5. HibernateUtil.java (for singleton ——> session)
  6. MyInterceptro.java (extends EmptyInterceptor available in Hibernate)
  7. FirstExample.java (main method class)

1)      Usermaster table

create table usermaster(

`sno` int(3) NOT NULL AUTO_INCREMENT,

`username` varchar(15) DEFAULT NULL,

`password` varchar(15) DEFAULT NULL,

`status` int(1) DEFAULT NULL,

PRIMARY KEY (`sno`)

)

2)      Usermaster.java (pojo class)

public class Usermaster {

private int sno;

private String username;

private String password;

private int status;

public int getSno() {

return sno;

}

public void setSno(int sno) {

this.sno = sno;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getStatus() {

return status;

}

public void setStatus(int status) {

this.status = status;

}

}

3)      Usermaster.hbm.xml

<?xml version=”1.0″?>

<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”

http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;

<!– Generated Mar 2, 2011 6:39:02 PM by Hibernate Tools 3.4.0.CR1 –>

<hibernate-mapping>

<class name=”com.shal.model.Usermaster” table=”usermaster”>

<id name=”sno” type=”java.lang.Integer”>

<column name=”sno” />

<generator />

</id>

<property name=”username” type=”string”>

<column name=”username” length=”30″ />

</property>

<property name=”password” type=”string”>

<column name=”password” length=”30″ />

</property>

<property name=”status” type=”java.lang.Integer”>

<column name=”status” length=”20″ />

</property>

</class>

</hibernate-mapping>

4)      Hibernate.cfg.xml

<?xml version=’1.0′ encoding=’utf-8′?>

<!DOCTYPE hibernate-configuration PUBLIC

“-//Hibernate/Hibernate Configuration DTD//EN”

http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;

<hibernate-configuration>

<session-factory>

<property name=”connection.useUnicode”>true</property>

<property name=”connection.characterEncoding”>UTF-8</property>

<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

<property name=”connection.url”>jdbc:mysql://localhost/test</property>

<property name=”connection.username”>root</property>

<property name=”connection.password”>gopal</property>

<property name=”show_sql”>true</property>

<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

<property name=”current_session_context_class”>thread</property>

<property name=”hibernate.transaction.factory_class”>org.hibernate.transaction.JDBCTransactionFactory</property>

<mapping resource=”com/shal/model/Usermaster.hbm.xml”/>

</session-factory>

</hibernate-configuration>

5)      HibernateUtil.java

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory()

{                                try {

// Create the SessionFactory from hibernate.cfg.xml

return new AnnotationConfiguration().configure().buildSessionFactory();

} catch (Throwable ex) {

System.err.println(“Initial SessionFactory creation failed.” + ex);

throw new ExceptionInInitializerError(ex);

}

}

public static SessionFactory getSessionFactory() {

return sessionFactory;

}

}

6)      MyInterceptor.java

public class MyInterceptor extends EmptyInterceptor {

private int updates;

private int creates;

private int loads;

public void onDelete(Object entity,Serializable id,Object[] state,String[] propertyNames,Type[] types) {

System.out.println(“Delete Operation”);

}

// This method is called when Employee object gets updated.

public boolean onFlushDirty(Object entity,Serializable id,Object[] currentState,Object[] previousState,String[] propertyNames,

Type[] types) {

if ( entity instanceof Object ) {

System.out.println(“Update Operation”);

return true;

}

return false;

}

public boolean onLoad(Object entity,Serializable id,Object[] state,String[] propertyNames,Type[] types) {

// do nothing

return true;

}

// This method is called when Employee object gets created.

public boolean onSave(Object entity,Serializable id,Object[] state,String[] propertyNames,Type[] types) {

if ( entity instanceof Object ) {

System.out.println(“Create Operation”);

return true;

}

return false;

}

//called before commit into database

public void preFlush(Iterator iterator) {

System.out.println(“preFlush”);

}

//called after committed into database

public void postFlush(Iterator iterator) {

System.out.println(“postFlush”);

}

}

7)      FirstExample.java

public class FirstExample{

public static void main(String args[])

{

Session session = HibernateUtil.getSessionFactory().openSession(new MyInterceptor());

session.beginTransaction().begin();

//Before Saving

Usermaster usermaster = new Usermaster();

try

{

usermaster.setUsername(“Gopal”);

usermaster.setPassword(“gopal123”);

usermaster.setStatus(new Integer(1));

session.save(usermaster);

session.beginTransaction().commit();

}catch(Exception e)

{

session.beginTransaction().rollback();

e.printStackTrace();

}

//Updating the record

try

{

Usermaster usermaster1 = (Usermaster)session.get(Usermaster.class,new Integer(1));

usermaster1.setPassword(“123gopal”);

session.update(usermaster1);

session.beginTransaction().commit();

}catch(Exception e)

{

session.beginTransaction().rollback();

e.printStackTrace();

}

//Deleting the Record

try

{

Usermaster usermaster2 = (Usermaster)session.get(Usermaster.class,new Integer(1));

session.delete(usermaster2);

session.beginTransaction().commit();

}catch(Exception e)

{

session.beginTransaction().rollback();

e.printStackTrace();

}

}

}

Output:

Create Operation

preFlush

postFlush

Update Operation

preFlush

postFlush

Delete Operation

preFlush

postFlush

hibernate inheritance

Posted: April 21, 2012 in Hibernate

Hibernate inheritance

In Front-End we have hierarchical data (inheritance)

In Back-End we don’t have hierarchical data (inheritance)

Front End and Back End model/formats is different. You cannot persist hierarchical data in Back End.

There is no inheritance concept in data base like oracle, mysql. But by using hibernate we can achieve. Everything done at hibernate level only.

Hibernate provides solution for the hierarchical data in different strategies like below.

  1. Table per class hierarchy
  2. Table per sub class
  3. Table per concrete class

Table per Class hierarchy:

In this strategy Hibernate allows you to persist sub class and super class information into a single table(entire hierarchy). And hibernate can distinguish the data belongs what particular sub class in the table based on discriminator column. The discriminator column value will be hard coded in the xml file. As it is not related to business. We are not mapping discriminator column to a pojo property.

Storing information in a single table we have to face “Sub Type” problem. To avoid this hibernate provides discriminator column in table per hierarchy.

Problem: (NOTNULL constraint)

In this strategy if we are persisting regular employee object the columns that is mapped to contract employee will be null vice versa. Suppose in our data base table if we are not interested to have a null value column means that column have constraint “NOT NULL”. Then this strategy is a failure one.

x number of classes = single  table in the database

Code in xml file:

<class name=”org.gopal.Employee” table=”employee”>

<id name=”eid” type=”java.lang.Long” column=”eid”>

<generator class=”assigned”>

</id>

<property name=”ename” column=”ename”/>

<discriminator column=”subtype”/>

<sub-class name=”org.gopal.RegularEmployee” discriminator-value=”regular”>

<property name=”salary” column=”salary”/>

</sub-class>

<sub-class name=”org.gopal.ContractEmployee” discriminator-value=”contract”>

<property name=”rateperhour” column=”rt_per_hour”/>

<property name=”hourperday” column=”hr_per_day”/>

</sub-class>

</class>

Table per sub class:

In this strategy for every class will be mapped to different tables. In our case employee is mapped to employee table. Regular employee is mapped to regular_employee table and contract employee is mapped contract_employee table.

regular_employee table has reference column which refer to employee table similarly

contact_employee table has reference column which refer to employee table.

Inside regular_employee or contact_employee we can have NOTNULL constraint also(drawback of class per hierarchy)

Problem: (joins)

If we want to read/get employee we should use joins. If we apply joins performance will be decrease when compare to reading a record from a single table.

x number of classes = x number of tables in the database

Code in xml file:

<class name=”org.gopal.Employee” table=”employee”>

<id name=”eid” type=”java.lang.Long” column=”eid”>

<generator class=”assigned”>

</id>

<property name=”ename” column=”ename”/>

<joined-subclass name=”org.gopal.RegularEmployee” table=”regular_emp”>

<key><column name=”eid”/> </key>

<property name=”salary” column=”salary”/>

</joined-subclass>

<joined-subclass name=”org.gopal.ContractEmployee” table=”contract_emp”>

<key><column name=”eid”/> </key>

<property name=”rateperhour” column=”rt_per_hour”/>

<property name=”hourperday” column=”hr_per_day”/>

</joined-subclass>

</class>

Table per Concrete class:

In this strategy Regular Employee and Employee information will persist into the regular_employee table and Contract Employee and Employee information will persist into the contract_employee table. Both these tables will persist employee information. Because of this eid, ename are became duplication in regular_employee and contract_employee tables.

Advantages:

1)      No need to execute the joins to get the data

2)      Apply NOTNULL constraints to the table columns.

Disadvantages:

1)      Duplication of  values like eid, ename.

x number of derived classes = x number of tables in the database

Code in xml file:

<class name=”org.gopal.Employee” table=”employee”>

<id name=”eid” type=”java.lang.Long” column=”eid”>

<generator class=”assigned”>

</id>

<property name=”ename” column=”ename”/>

<union-subclass name=”org.gopal.RegularEmployee” table=”regular_emp”>

<key><column name=”eid”/> </key>

<property name=”salary” column=”salary”/>

</union-subclass>

<union-subclass name=”org.gopal.ContractEmployee” table=”contract_emp”>

<key><column name=”eid”/> </key>

<property name=”rateperhour” column=”rt_per_hour”/>

<property name=”hourperday” column=”hr_per_day”/>

</union-subclass>

</class>

 

hibernate generators

Posted: April 21, 2012 in Hibernate

Hibernate software provides set of algorithms to generate identity values

1)      Assigned

2)      Increment

3)      Identity

4)      Native

5)      Sequence

6)      Hilo

7)      Seq hilo

8)      Guid

9)      Uuid

10)   Select

11)   Foreign

Assigned:

This algorithm uses programmer assigned value in primary key filed member variable of given pojo class object as identity value of the object

For every identity value generator algorithm, there will be a class and shortcut name. The class name of assigned algorithm is “org.hibernate.id.Assigned” and short cut name is assigned. All the classes that are acting as identity value generators implement a common interface called “org.hibernate.id.IdentifierGenerator”

<id name=”sno” column=”eid”>

<generator class=”org.hibernate.id.Assigned” or “assigned”/></id>

<id name=”sno” column=”eid”/> uses assigned as default algorithm, since no other

algorithm is explicitly specified.

Note:

In order to choose identifier generator algorithm we must consider the following two operations

a)      Ensure that the algorithm generated value is compatible with data type of identify field

b)      Ensure that underlying DB s/w is having provisions to support the algorithm

The algorithm assigned is compatible with all data types and supported by all database software

Increment Algorithm:

This algorithm generated identity values of type long or short or int that are unique. This algorithm works with all database software but can     generate only numeric values as identity values. The class name of this algorithm is “org.hibernate.id.IncrementGenerator”. This uses “(Max identity value + 1) as the formula to generate next identity value.

<id name=”sno” column=”eid”>

<generator class=”increment” (org.hiberante.id.IncrementGenerator)/> </id>

Sequence Algorithm: (doesn’t work with mysql)

This algorithm uses sequence concept available in DB2, postgreSQL, oracle, SAPDB …, and it generates identity values of type long,short,int. the class name of this algorithm is “org.hibernate.id.SequenceGenerator”.  To specify explicitly created sequence in database software as input values to this algorithm, use <param> having parameter name & value.

The sequence algorithm works only with the above listed database software

Procedure:

i)    Create sequence in underlying database software.

SQL> create sequence my_seq increment by 2;

ii)   Configure sequence algorithm by passing the sequence name as parameter value to the algorithm

<id name=”sno” column=”eid”>

<generator class=”sequence (or) org.hibernate.id.SequenceGenerator”>

<param name=”sequence”>my_seq</param>

</generator></id>

Identity algorithm:

This algorithm use identity value generated by identity columns available in DB2, mysql, SQL server, Sybase database software. This algorithm returns identifier value of type Long, short or int.

Identity column means the column that generates that’s its next record value by sing “Max value+1” formula

Note: To make ordinary column as identity column in mysql database software, we need to apply auto increment constraint on the table column. To apply increment constraint the column must be numeric data type column and the column should have primary key constraint.

The class name of this identifier algorithm is “org.hibernate.id.IdentityGenerator”

<id name=”sno” column=”eid”>

<generator class=”identity”/></id>

With respective to the above code the EID column of the table should act as identity column by having primary key, auto increment constraints.

Difference between increment and identity algorithm:

  • While working with increment algorithm the id field related table column need not to have any constraint [constraints are optional]. Whereas working with identity algorithm the id field related table column must having primary key, auto increment constraint.
  • Hibernate software generates increment algorithm based identity value.
  • The database software generates identity algorithm based identity value on identity column and hibernate software collects & uses that value.
  • Increment algorithm works with all database software
  • Identity algorithm works with only database software which support identity column (mysql, DB2 …)

Native algorithm:

This algorithm is not having its own individual behavior. This algorithm is capable of picking up identity, sequence or hilo algorithm based on the capabilities of underlying database software.

Due to this, algorithm works with all database software. While working with this algorithm, passing parameters is optional. But we can pass all the regular prams of sequence, hilo algorithms.

When native algorithm is configured by taking mysql underlying database software then it looks to work with identity algorithm.

When native algorithm is used by taking oracle as the underlying database software then  it use sequence algorithm to generates identity value.

If underlying database software does not support identity columns and sequence then the native algorithm looks to use hilo algorithm to generate id value.

Example:

<id name=”no” column=”eid”>

<generator class=”native”/>

</id>

In the above code native algorithm uses identity algorithm

<id name=”no” column=”eid”>

<generator class=”native”>

<param name=”sequence”>my_seq</param>

</generator>

</id>

In the above code native algorithm uses sequence algorithm internally

<id name=”sno” column=”eid”>

<generator class=”native”>

<param name=”table”>mytable</param>

<param name=”column”>mycol</param>

<param name=”max_lo”>10</param>

</id>

In the above code native algorithm uses hilo algorithm internally.

Note:

In order to work with native algorithm first try to notice which algorithm it is using internally for the underlying database software. Based on this you start configuring parameters while working with native algorithm.

Universal Unique Id Algorithm: (UUID)

This algorithm generates identifiers of type string which is unique with in a network (uses IP address). This algorithms use identifier values as encoded string of hexadecimal digits of length 32. This algorithm works with all database software. The class name of this algorithms is “org.hibernate.id.UUIDHexGenerator”. This algorithm generated id value is dynamic & random value.

Example: set up required [changes must be done in the following areas]

1)   Desc employee;

Field                               type

Firstname               varchar(20)

Lastname               varchar(20)

Email                       varchar(20)

2)   Hibernate pojo class (EmpBean)

Employee{

Private String no;

Private String fname,lname,mail;

}

3)      Coding mapping file

<id name=”no” column=”eid”>

<generator class=”uuid”/>

</id>

 

Global Unique Id Algorithm (guid)

This algorithm uses “new id()” available in sql to generate string based dynamic & random identifier value. This algorithm works only with mysql server & mysql database software. The class name of this algorithm is “org.hibernate.id.GUIDGenerator”

Note:

Uuid algorithm makes hibernate software to generate String based id value. GUID algorithm make underlying database software to generate id value and hibernate software uses that value.

Select Algorithm:

This algorithm take the database trigger generated value as id value of hibernate pojo class object. The class name is “org.hibernate.id.SelectGenerator”

Foreign Algorithm:

This algorithm is useful to generate id value in one pojo class object by collecting identity value form another pojo class object. This algorithm is very useful in one-to-one association mapping. The class name of this algorithm is “org.hibernate.id.ForeignGenerator”

Hilo (high and low) algorithm:

This algorithm generates identifiers of type long, short, int by using given table and its column as the source of ‘high’ values. The class name of this algorithm is “org.hibernate.id.TableHiLoGenerator”

This algorithm requires 3 mandatory parameters. Table, column, Max_lo

The column in the special table keeps track of the number of records that are inserted using this HiLo algorithm.

When multiple identity values are generated using this Hilo algorithm, the difference between each two values is (“Max_lo value+1”). This algorithm works with all database software.

Example: SQL> select * from mytable;

Mycol

400   —-> you can insert any value

<id name=”sno” column=”eid”>

<generator class=”hilo”>

<param name=”table”>mytable</param>

<param name=”column”>mycol</param>

<param name=”max_lo”>10</param>

</id>

Note: The first id value that has come through this algorithm is dynamic and random value. For this algorithm table must be empty.

Seqhilo algorithm:

This algorithm uses given database sequence and max_lo parameter value to generate identifiers of type long, short or int. This algorithms works with only in those database software which supports sequence

This algorithm having 2 mandatory parameters

-sequence

-max_lo

When multiple values (identity) are generated using this algorithm, the difference between two id values will be [increment by value of (sequence) * max_lo value] + [increment value of (sequence)]

The first id value generated by this algorithm is random value.

<id name=”sno” column=”eid’>

<generator class=”seqhilo”>

<param name=”sequence”>my_seq</param>

<param name=”max_lo”>10</param>

</generator>

</id>

Conclusion:

  • If identity filed member variable data type is numeric data type then use increment (or) native algorithms.
  • If identity filed data type is other than numeric data type use assigned algorithm and generate id value manually.

 

 

hibernate relationship

Posted: April 19, 2012 in Hibernate

Introduction To Relationships

Foo

The basic Foo looks like this:

Public class Foo

{

Protected int id;

Public Foo()

{

}

Public void setId(int id)

{

}

Public int getId()

{

}

}

Foo’s basic mapping looks like this:

<hibernate-mapping>

<class name=”Foo” table=”foo”>

<id name=”id” column=”id” type=”int”>

<generator class=”assigned”/>

</id>

</class>

</hibernate-mapping>

Bar

The basic bar looks like this

Public class Bar

{

Protected int id;

Public Bar()

{}

Public void setId(int id)

{

}

Public int getId()

{

}

}

Bar’s basic mapping look like this

<hibernate-mapping>

<class name=”Bar” table=”bar”>

<id name=”id” column=”id” type=”int”>

<generator class=”assigned”/>

</id>

</class>

</hibernate-mapping>

For both Foo and Bar are choosing to an assigned id generator. There is nothing special about this choice. We are simply choosing to program our ids manually.

1.       Simple Association (one-to-one)

Definition:

Our first relationship is a simple association. In this relationship, one first-rank class holds a reference to a single instance of another first-rank class and they are by a common PK.

Scenario:

We have two first-rank classes, Foo and Bar which are related to each other as follows:

Bar Foo.getBar() // returns corresponding Bar instance

Hibernate Mapping:

In hibernate, this could be mapped as follows:

<class name=”Foo” table=”foo”

<one-to-one name=”bar” class=”Bar”/>

</class>

Table Schema:

Foo
id
Bar
id

 

No extra columns are needed to support this relationship. Instead both Foo and Bar must share the same PK values to be part of a one-to-one association.

If you create suitable instances of Foo and Bar with a shared PK, then retrieving a Foo will automatically retrieve the corresponding Bar.

Bi directionality:

This relationship can be bi directional, with Bar having getFoo(), by simply adding a similar maping and Foo property to Bar.

2.       Simple Reference (many-to-one)

Definition:

A many-to-one reference is analogous to a simple Java reference. It is as the one-to-one situation except there is no requirement to have a shred PK. Instead a FK is used.

Scenario:

We have two first-rank classes, Foo and Bar which are related to each other as follows:

Bar Foo.getBar()   // returns corresponding Bar instance

Hibernate Mapping:

In hibernate, this could be mapped as follows:

<class name=”Foo” table=”foo”>

…….

<many-to-one name=”bar” class=”Bar” column=”bar_id”/>

</class>

Table Schema:

Foo
Id bar_id

.

Bar
Id

Now we have created an extra column in Foo’s table which holds the FK to Bar. Foo and Bar can have completely different PKs and the relationship will still hold.

Bi directionality:

This relationship can be declared both ways, with Bar having getFoo(), by simply adding similar mapping and property to Bar. This will result in Bar’s table getting an extra column foo_id.

3.       Basic Collection (one-to-many)

Definition:

A one-to-many reference is basically a collection. Here A first-rank class, a holds a reference to a collection of another first-rank class, B.

Scenario:

       We have two first-rank classes, Foo and Bar which are related to each other as follows:

Set Foo.getBars()    // returns collection of Bar instances

Hibernate Mapping:

In hibernate, this could be mapped as follows:

<class name=”Foo” table=”foo”>

…….

<set role=”bars” table=”bar”>

    <key column=”foo_id”/>

   <one-to-many class=”Bar”/>

</set>

</class>

We will mostly use <set> type collections in these examples except where we are examining specific collection-type features. Please refer to the hibernate documentation to learn about the comprehensive set of collection types available.

Table Schema:

Foo
Id
Bar
Id foo_id

Now we have created an extra column in Bar’s table which holds the FK to Foo. This allows Foo to be assigned a Collection of Bar’s based on the value of the foo_id column in Bar.

Bi directionality:

This relationship can be declared both ways, with Bar having getFoo(), by suitable code changes to Bar and the following schema change:

<class name=”Bar” table=”bar”>

……

<many-to-one name=”foo” class=”Foo” column=”foo_id”/>

</class>

Now your Bar’s will know who their Foo is.

Extra columns are generated for the bi directionality.

4.       Collection (many-to-many)

Definition:

A many-to-many reference is basically a collection. First-rank class A holds a reference to a set of first-rank class B instances (as in the one-to-many case), but B might have multiple A’s.

Scenario:

We have two first-rank classes, Foo and Bar which are related to each other as follows:

Set Foo.getBars()   //returns a collection of Bar instances

Hibernate Mapping:

<class name=”Foo” table=”foo”>

….

<set role=”bars” table=”foo_bar”>

<key column=”foo_id”/>

<many-to-many column=”bar_id” class=”Bar”/>

</class>

Table Schema:

Foo
Id
Bar
Id
Foo_Bar
foo_id bar_id

This time we cannot have an extra column on Bar as that would dictate that each Bar has only one Foo.  So instead we have an extra table, foo_bar, which holds the relationship between

Bi directionality:

This relationship can be declared both ways, with Bar having getFoos(), by suitable code changes to Bar and the following schema change:

<class name=”Bar” table=”bar”>

…….

<set role=”foos” table=”foo_bar” read-only=”true”>

<key column=”bar_id”/>

<many-to-many column=”foo_id” class=”Foo”/>

</set>

</class>

Now your Bar’s will know who their Foo’s are

No extra columns are generated for bi directionality.

Note that one end of the relationship must be declared “readonly”.

 

jpa second level cache

Posted: April 14, 2012 in Hibernate

Hibernate3 – JPA Annotations (Second Level Cache)

Here I used technologies are hibernate3, JPA, Servlet, Eclipse Helios (IDE)

Project Structure:

Hibernate-JPA-SecondLevelCache

src

com.shal.controller

| —>  MyController.java

com.shal.model

|—> Product.java

com.shal.util

|—>HibernateUtil.java

META-INF

|—>persistence.xml

hibernate.cfg.xml

ehcache.xml

WebContent

Index.jsp

WEB-INF

|—> web.xml

lib

|—> ehcache-1.2.3.jar (rest of the jar’s u hv seen in my previous one)

1)        Create a table in database named as products

CREATE TABLE `products` (

`pid` int(4) NOT NULL AUTO_INCREMENT,

`pname` varchar(25) DEFAULT NULL,

`price` double DEFAULT NULL,

PRIMARY KEY (`pid`)

) ENGINE=InnoDB AUTO_INCREMENT=107 DEFAULT CHARSET=latin1

Insert values into products(1,”gopal”,5000)

Insert values into products(2,”satya”,6000)

2)       MyController.java (Servlet)

package com.shal.controller;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import org.hibernate.criterion.Restrictions;

import com.shal.model.Product;

import com.shal.util.HibernateUtil;

public class MyController extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

Session session =HibernateUtil.getSessionFactory().openSession();

session.beginTransaction().begin();

try{

int no = Integer.parseInt(req.getParameter(“productId”));

Product  product=(Product)session.createCriteria(Product.class)

.add(Restrictions.eq(“pid”,no))

.setCacheable(true)

.uniqueResult();

System.out.println(“Name “+product.getPname()+”Price

“+product.getPrice());

}

catch (Exception e) {

// TODO: handle exception

session.beginTransaction().rollback();

e.printStackTrace();

}

finally{

session.close();

}}}

3)  Product.java

package com.shal.model;

import java.io.Serializable;

import javax.persistence.*;

import org.hibernate.annotations.Cache;

import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity

@Table(name=”products”)

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

public class Product implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@Column(unique=true, nullable=false)

private int pid;

@Column(length=25)

private String pname;

private double price;

public Product() {

}

//setters and getters for all fields

}

4)       HibernateUtil.java

package com.shal.util;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory()

{

try {

// Create the SessionFactory from hibernate.cfg.xml

return new AnnotationConfiguration().configure().buildSessionFactory();

} catch (Throwable ex) {

System.err.println(“Initial SessionFactory creation failed.” + ex);

throw new ExceptionInInitializerError(ex);

}                }

public static SessionFactory getSessionFactory() {

return sessionFactory;

}}

5)       persistence.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<persistence version=”2.0″ xmlns=”http://java.sun.com/xml/ns/persistence&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd”&gt;

<persistence-unit name=”Hibernate-JPA-SecondLevelCache”>

<class>com.shal.model.Product</class>

</persistence-unit>

</persistence>

6)       ehcache.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<ehcache>

<defaultCache maxElementsInMemory=”100″ eternal=”false” timeToIdleSeconds=”120″ timeToLiveSeconds=”200″ />

<cache name=”com.shal.model.Product” maxElementsInMemory=”100″ eternal=”false” timeToIdleSeconds=”200″ timeToLiveSeconds=”200″ />

</ehcache>

 7)       hibernate.cfg.xml

<hibernate-configuration>

<session-factory>

<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

<property name=”connection.url”>jdbc:mysql://localhost/gopal</property>

<property name=”connection.username”>root</property>

<property name=”connection.password”>shal</property>

<property name=”cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>

<property name=”cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>

<property name=”cache.use_query_cache”>true</property>

<property name=”cache.use_second_level_cache”>true</property>

<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>

<property name=”show_sql”>true</property>

<property name=”hbm2ddl.auto”>update</property>

<mapping class=”com.shal.model.Product”></mapping>

</session-factory>

</hibernate-configuration>

8)       web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; id=”WebApp_ID” version=”2.5″>

<display-name>Hibernate-JPA-SecondLevelCache</display-name>

<servlet>

<servlet-name>dopost</servlet-name>

<servlet-class>com.shal.controller.MyController</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>dopost</servlet-name>

<url-pattern>/dopost</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

9)       index.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″

pageEncoding=”ISO-8859-1″%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;

<html><head/>

<body>

<form action=”dopost” method=”post”>

<center>

Enter Product Number:

<input type=”text” name=”productId”></input>

<input type=”submit” value=”send”></input>

</center>

</form>

</body>

</html>

hibernate second level cache

Posted: April 14, 2012 in Hibernate

Second – Level Cache Using Hibernate:

A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database and put it whether in memory or in file. Database access is necessary only when retrieving data that is not currently available in the cache. So basically not all queries are taken from database, but from cache instead.

1)        Create a table in database named as products

CREATE TABLE `products` (

`pid` int(4) NOT NULL AUTO_INCREMENT,

`pname` varchar(25) DEFAULT NULL,

`price` double DEFAULT NULL,

PRIMARY KEY (`pid`)

) ENGINE=InnoDB AUTO_INCREMENT=107 DEFAULT CHARSET=latin1

Insert values into products(1,”gopal”,5000)

Insert values into products(2,”satya”,6000)

2)       Create pojo class in our project

         package com.shal;

        public class Product {

private int productId;

private String proName;

private double price;

//setters and getters

}

3)       Create hibernate.cfg.xml as usual

<hibernate-configuration>

<session-factory>

<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

<property name=”connection.url”>jdbc:mysql://localhost/gopal</property>

<property name=”connection.username”>root</property>

<property name=”connection.password”>shal</property>

<!—we hv to tell hibernate that we wanted to use second level cache

Here I am using one of the hibernate cache like EhCacheProvider –>

<property name=”cache.provider_class”>org.hibernate.cache.EhCacheProvider   </property>

<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>

<!—show_sql true is needed whether the query hitting database for every time —>

<property name=”show_sql”>true</property>

<property name=”hbm2ddl.auto”>update</property>

<mapping resource=”Product.hbm.xml”></mapping>

</session-factory>

</hibernate-configuration>

4)       Create ecache.xml (its new)

<?xml version=”1.0″ encoding=”UTF-8″?>

<ehcache>

<defaultCache maxElementsInMemory=”100″ eternal=”false” timeToIdleSeconds=”120″ timeToLiveSeconds=”200″ />

<cache name=”com.shal.Product” maxElementsInMemory=”100″ eternal=”false” timeToIdleSeconds=”5″ timeToLiveSeconds=”200″ />  </ehcache>

<ehcache>

<diskStore path=”java.io.tmpdir”/>                    (1)

<defaultCache

maxElementsInMemory=”10000″                       (2)

eternal=”false”                                                          (3)

timeToIdleSeconds=”120″                                    (4)

timeToLiveSeconds=”120″                                   (5)

overflowToDisk=”true”                                          (6)

/>

</ehcache>

diskStore : Sets the path to the directory where cache .data files are created. The following properties are translated:

a.user.home – User’s home directory

b.user.dir – User’s current working directory

c.java.io.tmpdir (Default temp file path)

maxElementsInMemory : Sets the maximum number of objects that will be created in memory.

eternal : Sets whether elements are eternal. If eternal,  timeouts are ignored and the element is never expired.

timeToIdleSeconds : Sets the time to idle for an element before it expires. Is only used if the element is not eternal. Idle time is now – last accessed time.

timeToLiveSeconds : Sets the time to live for an element before it expires. Is only used if the element is not eternal. TTL is now – creation time

  • overflowToDisk : Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit.

Finally the cache concurrency strategy has to be specified in mapping files. For example, the following code fragment shows how to configure your cache strategy

5)       Create product.hbm.xml

<hibernate-mapping>

<class name=”com.shal.Product” table=”products”>

<cache usage=”read-only” /> <!— read-only , read-write …., —>

<id name=”productId” column=”pid”  />

<property name=”proName” column=”pname” length=”10″/>

<property name=”price”/>

</class>

</hibernate-mapping>

6)       Create main

package com.shal;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class EhCacheExample {

public static void main(String[] args)

{

Configuration cfg = new Configuration();

cfg.configure(“hibernate.cfg.xml”);

SessionFactory factory = cfg.buildSessionFactory();

Session session1 = factory.openSession();

Object o=session1.load(Product.class,new Integer(105));

Product s=(Product)o;

System.out.println(“Loaded object product name is___”+s.getProName());

System.out.println(“Object Loaded successfully…..!!”);

session1.close();

System.out.println(“——————————“);

System.out.println(“Waiting……”);

try{

Thread.sleep(6000);

}

catch (Exception e) {

}

System.out.println(“6 seconds compelted……!!!!!!!!”);

Session session2 = factory.openSession();

Object o2=session2.load(Product.class,new Integer(105));

Product s2=(Product)o2;

System.out.println(“Loaded object product name is___”+s2.getProName());

System.out.println(“Object loaded from the database…!!”);

session2.close();

Session session3 = factory.openSession();

Object o3=session3.load(Product.class,new Integer(105));

Product s3=(Product)o3;

System.out.println(“Loaded object product name is___”+s3.getProName());

System.out.println(“Object loaded from global cache successfully…..!!”);

session3.close();

factory.close();

}

}

Output:

Hibernate: select product0_.pid as pid0_0_, product0_.pname as pname0_0_, product0_.price as price0_0_ from products product0_ where product0_.pid=?

Loaded object product name is___BC

Object Loaded successfully…..!!

——————————

Waiting……

6 seconds compelted……!!!!!!!!

Hibernate: select product0_.pid as pid0_0_, product0_.pname as pname0_0_, product0_.price as price0_0_ from products product0_ where product0_.pid=?

Loaded object product name is___BC

Object loaded from the database…!!

Loaded object product name is___BC

Object loaded from global cache successfully…..!!

Project Structure:

MyProject

src

com.shal

EhCacheExample.java

Product.java

hibernate.hbm.xml

product.hbm.xml

ehcache.xml

Used jar files:

 

mysql-connector-java-3.1.12-bin.jar

antlr-2.7.6.jar

asm.jar

cglib-2.1_3.jar

commons-collections-2.1.1.jar

commons-logging-1.0.4.jar

dom4j-1.6.1.jar

ehcache-1.2.3.jar

hibernate-3.2.6.ga.jar

jta.jar