Hibernate (1) Notes
Hibernate (1) Notes
Step 1: Get the server view and right click chooses an option configure
server connector.
Step 2: Choose the appropriate server the home directory of the server.
Same servers
required user name and password supply these values and click
on OK.
Step 3: To add the project to server we can use an option add
deployment.
Step 4: They are some IDEs are available which are responsible to
interact with database
Servers. The popular IDEs for oracle database server are TOAD
and SQL developer.
For the database server like MYSQL we
can use
MYSQL workbench.
Step 5: In the companies because of licenses issues we may not use the
IDE like TOAD.
Eclipse gives has provided a feature to interact with database
servers. We can use
Eclipse/MYECLIPSE to interact with database servers.
*Procedures to configure IDE to interact with database server:
1. Open MYECLIPSE database explorer of prospective.
2. In the database browser view when we right click it lunches a popup
menu from that choose an option new.
3. The above step as lunched a window whose name is database
driver from that choose driver template and provide a driver name.
Now we have to supply driver class, url, username, password to
interact with DB server.
*Hibernate is a frame which is used to interact with database
server:
There are so many frameworks are available in the market there are
some of struts, springs, JSF etc.
1. Struts, spring frame works are used to develop web-based
applications.
2. Hibernate is a technology are a framework which is used to interact
with database server this framework resolves all the problems of
1
retrieve data from result set object and store it in array list object if
we use Hibernate. Hibernate does all these work.
14.
*we have the technology like EJB to
interact with DB Server we cant run EJB Application without EJB
container. We cant use EJBs in all type of application we can
resolve all these problems we can use Hibernate.
*The following is true Architecture of Hibernate framework.
JAVA Application
Hibernate S/W
JDBC API
DB Server
*Hibernate is called as ORM tool are ORM framework ORM (Object
Relational Mapping).
In the market they are so many ORM frame works are available some of
them ere Hibernate, JPA (java persistent API) JDO (java data object) i
batches, STO (service data o/p), Top Link etc.
All these frame works are used as ORM Tools. The differences between
the Tools are the names of the classes are different.
In the database server the data will be stored in the side the tables
between the tables we establish a relationship because of this reason we
call it is relational data.
1
2
3
1
Pone
100
Pno
100
pname
2000
price
3000
Product
2
PTwo
2000
11.
In our database
server we have two tables emp and product. We need to develop
two pojo classes.
a. Emp.java
b. Product.java
Note: There is no rule saying protocol names and tables name
must be same.
public class employee{
int eno;
string ename;
string eddress;
public void set eno(int eno)
{
this.eno = eno;
}
public int geteno(){
return eno;
}
12.
We
have
to
develop Hibernate mapping files. These files contain. The
information about which protocol class is mapped with which table
and which properties mapped with which column.
Employee
(POJO)
Emp
(Table)
EMPNO
ENO
EMPNAME
NAME
EMPADDRESS ADDRESS
emp.hbm.xml
Note:
IDE takes care of generating Hibernate configuration file, pojo
classes and Hibernate Mapping files.
*The POJO classes must following rules:
1
Hibernate3.jar
Hibernate S/W
JTA.ja
r
C3P.j
ar
Cach
e.jar
Dom.j
ar
.. Etc
VI.
VII.
hsession.close();
sf.close();
}
}
This method is an expensive operation in a project it is recommended to
call the configure method only once in the project life cycle.
In any frame wrote we can change the configuration file name according
to our requirement.
If you are using our own configuration file name we have to use the over
loaded configuration method.
Ex: cfg.configure(myproject.xml);
Note:
The default configure method always check for hibernate cfg.xml
file. It always recommends using .cfg in the configuration file name.
Because of this we can easily recognize the configuration file name.
configuration();
hibernate.cfg.xml
*.hbm.xml
When we call cfg.build SessionFactory() method it gets driver class, url,
username and password these values are supplied as input to hibernate
internal connection pool. Now the hibernate internal connection pool. Get
the connections from database servers.
tables. If you
an additional
the following
configuration
session
TBS
Cache
When we call tx.commit hibernate got first level cache and check are
there any object are available in first level cache it the objects are
available hibernate check. The registration code of the object hibernate
find to which POJO class this object is created and to which table this
POJO class is mapped.
Based on the table name and registration and hibernate get the insert
query from the JVMs memory. It is the responsibility hibernates to
replace positional parameters with appropriate values from the object.
Now the hibernate add the query to batch object.
Now the hibernate send the batch object to Database server if it got
execute successfully it returns an identifies value. If the batch is failed it
throws an exception batch update exception.
Hibernate send a sql query to Database server to see the sql query sent
by hibernate we can add property show-sql. This attribute takes a
Boolean value.
Ex:
<property name = show_sql>true</property>
To see all the messages are work done by hibernate we can use
log4j.properties.
log4j.root logger = DEBUG/A1
log4j.appender.A1 = org.APAche.log4j.console
Appender
log4j.appender.A1.layout =
We can use a method persist to store the data into database server.
Syntax: void persist(object)
Ex: serializable save(object)
When we generate hbm files and POJO classes in hibernate by using IDE
based on the column data type IDE generate the appropriate data type in
POJO class for example eno number(15) IDE uses big decimal data type
for eno number(2) IDE uses byte and etc.
As part of java5.0 sun micro system as added a feature auto boxing. The
advantage of auto boxing is we LAN directly convert primitive data type
values to wrapper classes.
Ex:
int a = 10;
integer i = a;
system.out.println(i);
When we trying to dual with auto boxing for double data type as shown
below we are getting the compilation error.
Ex: Double d = 20d;
*develop a Hibernate application to retrieve a record from emp table
where eno is 2?
public class RetrieveRecords{
public static void main(String[] args){
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Emp e = new Emp();
Hsession.load(e,new Bigdecimal(2));
System.out.println(e.getEno());
System.out.println(e.getName());
System.out.println(e.getSalary());
hession.close();
}
}
When we call the load() method the internal code of Hibernate has
performed the following steps.
Step 1: It has checked the corresponding POJO class name for the
supplied object.
Step 2: It has checked this POJO class object is mapped to which table for
that table Hibernate has picked appropriate select query. The following is
the query available in JVMs memory.
Select eno, name, salary from emp where eno =? Now the
Hibernate has replaced the positional parameter value with 2 and
send the query to database server.
Database server has executed the select query and represented the
records in the result set object and given into hibernate software.
Hibernate software has taken from ResultSet object and by using
the getter method got the data from ResultSet object and stored it
in POJO class object.
Now the Hibernate added the POJO class object to 1 st level cache.
Note: If we try to call a load cs method on a non available record
Hibernate
throw
an
exception
saying
org.hibernate.ObjectNotFoundException.
To check weather any object is available in 1 st level cache or not we can
use a method contains().
Sybtax: boolean Contains(object)
*Write a hibernate application to delete the records from product table
whose productID is 11.To delete the records from hibernate we can use
two approaches.
Approach 1: Load the record and mark the object as to delete.
public class DeleteRecords{
public static void main(String[] args){
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Transaction tx = hsession.beginTransaction();
Product p = new Product();
hsession.load(p,11);
// step 1
hsession.delete(p);
// step 2
tx.commit();
// step 3
hsession.close();
}
}
Step 1: when step 1 is executed it has retrieve the records whose
primary key value is 11 and add into 1st level cache.
Step 2: When we call the method object is marked as to be deleted.
Step 3: when we call the commit method the hibernate software got the
delete query and replaces the positional parameter with primary key
value and send the query to database server.
In this approach first we are checked in whether the record is available or
not if the record is not available. The load() method throws object not
found exception.
Approach 2: Create the POJO class object and supply the primary key
value. Mark the POJO class object as to be deleting by calling the delete
method.
Ex:
public class DeleteRecords1{
public static void main(String[] args){
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Product p = new Product();
p.setpid(11);
hsession.delete(p);
tx.commit();
hsession.close();
}
}
In this approach when we call the delete method object is marked as to
be deleted. When we call the commit() method it has perform the
following 3 steps.
Step 1: It check weather primary key value is available in the supplied
object or not. If not available it will not carry out any work.
Step 2: If the primary key value is available a select query will be send to
database server to check weather record is available or not.
Step 3: If the record is available in DB hibernate send the delete query. If
the record is not available hibernate will not do any work.
Approach 1: Updating a record into database server which ever the
record we would like to update load the record by calling load() method
modify the values by using setter methods in the loaded POJO class
object. Now mark the object as to be updated.
Ex:
public class UpdateRecord{
public static void main(String[] args){
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Emp e = new Emp();
hsession.load(e, new BigDecimal(2));
e.setName(Raju);
hsession.update(e);
tx.commit();
hsession.close();
}
}
*Connection():
This method is used to get legacy database connection.
Generally this is not recommended approach in hibernate. We use this to
perform some operations which can not be done by using hibernate.
Ex:
Session hsession = sf.openSession();
Transaction tx = hsession.beginTransaction();
Connection con = hsession.Connection();
Statement stmt = con.createStatement();
stmt.executeUpdate(Insert into emp values(2,sadaf,234));
tx.commit();
In Hibernate when we get the connection object by default auto commit
mode to false.
We have multiple over loaded methods as for session interface they are:
void load(object, pid)
object load(class, serializable)
Ex:
Class c = class.forName(info.inetsolv.product);
Object o = hsession.load(c,l);
Product p = (product)o;
System.out.println(p.getPid());
System.out.println(p.getName());
System.out.println(p.getPrice());
When we call the above load() method if the record is available load()
method creates POJO class object and store the data and return POJO
class object if the record is not available load() method will not create
POJO class object.
We have a static variable class as part of object class when ever we call
that variable by using class name it returns the calling class classobject.
Ex:
Cone.class
When the above code is executed it has return class object.
name =
Cone
package =1
null
Class
*get():
get() method is also used to retrieve the record from database server if
the record is available it returns that POJO class object. If record is not
available it returns null value.
Ex:
Object o = hsession.get(product.class,2);
If(o! = null){
Product p = (product)o;
System.out.println(p.getPid());
System.out.println(p.getName());
System.out.println(p.getPrice());
}
else{
System.out.println(Record is not available);
}
*flush():
When we call in flush() method all the objects which are
available in 1 level cache will be converted into queries and send to
database server. Flush will not store data permanently. When we all the
commit() method the data is stored permanently.
st
Hibernate S/W
Hibernate.properties
or
Hibernate.cfg.xml
Database Server
Step 1: Create a table in the data base server.
Step 2: Get the Hibernate software and placed in a lib folder (copy
ojdbc14.jar also).
Note:
We can get the jar files from IDE.
Step 3: Develop a cmd file which contains the class path to all the
Hibernate related jar files.
Ex: Set CLASSPATH=lib\antlr.2.7.6.jar;lib\C3P0-0.9.1.jar;
Step 4: Create the POJO class. We can use any class name as POJO class
name for example.
</hibernate-configuration>
Develop a java application to store the data into database server.
The parser program check for hibernate dtd file as part of hibernate file.
As part of hbm file we can remove the column tag or attribute if the POJO
class properties and column names are same.
*The following is sample configuration for emp table.
<hibernate-mapping>
<class name = info.inetsolv.Employee>
<id name = employeeNo/>
<property name = employeeName/>
<property name = employeeSalary/>
</class>
</hibernate-mapping>
We can club multiple hbm files into a simple hbm file. But this approach
is not recommended for big projects, it is recommended to use one hbm
file BrOne one POJO class.
<hibernate-mapping>
<class name = info.inetsolv.Employee>
<class name = info.inetsolv.Product>
<id name = Pid access = field/>
<property name = name class = field/>
</class>
</hibernate-mapping>
We can develop hibernate application with out hibernate configuration
file. But we have to provide the properties and mapping files through the
java program.
Ex:
public class Store{
public static void main(String[] args){
Configuration cfg = new Configuration();
cfg.setProperty(hibernate.connection.driver_class,oracle.jdbc.driver.Or
acleDriver);
cfg.setProperty(hibernate.connection.url,jdbc:oracle:thin:@localhost:1
521:xe:);
cfg.setProperty(hibernate.connection.username,hib);
cfg.setProperty(hibernate.connection.password,abc);
cfg.setProperty(hibernate.dialect,org.hibernate.dialect.Oracle9Dialect
);
cfg.setProperty(hibernate.show_sql,true);
cfg.addResource(a.hbm.xml);
sessionFactory sf = cfg.buildSessionFactory();
session hession = sf.openSession();
..
.
}
}
Instead of addResource() method we can use addClass() method.
Ex:
cfg.addClass(info.inetsolv.product.class);
when we use addClass() it will check for info.inetsolv.product.hbm.xml
file.
The disadvantage of programmatic configuration is when Hard coding
the values in the java program. If we want to communication with same
hibernate application with different database server. We have to change
the java code because of this reason this approach is not recommended.
Generally in the projects we use properties files to remove hard coding.
Most of the projects uses property file end with an extension dot (.)
properties inside the properties file we supply a data in the form of key
and value.
Ex:
Key = value
//myproject.properties
We can configuration hibernate parameters as part of a property-file.
Whos name is hibernate properties.
Ex:
hibernate.connection.driver_class = oracle.jdbc.driver.OracleDriver
hibernate.connection.url = jdbc:oracle:thin:@localhost:1521:xe
hibernate.connection.username = hib
hibernate.connection.password = abc
hibernate.dialect = org.hibernate.dialect.Oracle9Dialect
hibernate.show_sql = true
//save hibernate.properties
Its not recommended to use property file as part of hibernate. This is
because as part of the property file are cant configuration the mapping
resource files.
We can supply the values by the properties using system properties
when we run the application.
Ex: -Dhibernate.connection.driver_class = oracle.jdbc.driver.OracleDriver
Meagerly hibernate is divided into three parts. They are:
Connection Management
ORM
Transaction Management
Hibernate S/W
Hibernate S/W is good at ORM as well as transaction management the
internal hibernate code uses two connections pools C3P, DBCP. Its not
recommended to use there connection pools. Its always recommended
to use the external connection pool like weblogic connection pool.
*Using procedure to use weblogic connection pool program in hibernate.
1. Configure weblogic server connection pool by specify JNDI name.
2. Get the hibernate S/W place in lib folder and set the class path.
3. Create POJO class and hbm file.
4. Create hibernate configuration file with data source, username and
password and jndi.class and jndi.url
<hibernate-configuration>
<Session-Factory>
1
5.
6.
7.
8.
<property
name=hibernate.connection.datasource>mypool</property>
<propery
name=hibernate.connection.username>admin</property>
<propery
name=hibernate.connection.password>inetsolv</property>
<propery
name=hibernate.jndi.class>weblogic.jndi.WLInitialContextFactory
</property>
<propery
name=hibernate.jndi.url>t3://localhost7001/</property>
<propery name=hibernate.show_sql>true</property>
<mapping resource = a.hbm.xml/>
</Session-Factory>
</hibernate-configuration>
Develop the hibernate application to store the data into database
server.
Note: we have set the class path to web.jar or set DomainEnv.cmd
When we are configuration are using connection pool as part of
hibernate we have choose use jndi data source rather then jdbc
driver.
To
set
the
class
path
to
resolve
the
problem
of
weblogic.jndi.WLInitialContextFactory we are added weblogic.jar in
the class path.
Hibernate can be used to communicate with any DB server.
}
}
When we compile the above program the compiler reports error message
saying null value can not be assigned to primitive data types. we can
assigned a null value to wrapper classes.
Ex:
public class MyApp{
public static void main(String[] args){
Integer a = null;
System.out.println(a);
}
}
As part of the IDE when we generating hbm files and POJO classes we
have an option. We have primitive data types or wrapper classes. They
are java types and hibernate types.
When we choose java types it uses wrapper classes. When we choose
hibernate types it uses primitive data types.
We are try to use primitive data types and trying to store data into
tables. In these scenarios the default values of primitive data types are
getting store into data base server.
Ex:
Product p = new Product();
p.setPid(Pid);
p.setName(Pname);
hsession.save(p);
When we execute the above code even though when the user is not
supplied price value application has stored 0.0 values.
When we use primitive data types to retrieve records from a table which
contains null values. then the application throwing an exception.
org.hibernate.propertyAccessExcepton.
By using JDBC also we can represent the records in the form of objects.
The following is an example of representing data in the form of object by
using JDBC?
Ex:
JDBC Application
Driver class
url
username,
password
Property files
querys
DB Server
Oracle
MySqle
DB2
3. The database server executes select query and return the ResultSet
object to hibernate S/W.
4. Hibernate S/W represents every record in the form of object and add
it to array list object.
5. List() method converts ArrayList into supper class reference variable
list and it returns it we have to get ArrayList object and display
records to client.
When we trying to add any element to ArrayList object it will be
converted into supper class object called as object. While retrieving data
from ArrayList we need to typecast into appropriate object.
As part HQL queries we can add where conditions as well as order by
clause, group by clause.
*using where clause as part of HQL:
SQL> select * from emp where eno>2;
HQL> from info.inetsolv.Employee where employee>2;
*using positional parameters in HQL:
The following is an example of using positional parameters in HQL.
SQL> select * from product where price >? And price<?
HQL> from product where price>? And price>?
Ex:
String query = from product where price>? And price<?;
Query hqlquery = hsession.createquery(query);
hqlquery.SetDouble(0,2000);
hqlquery.SetDouble(1,5000);
ArrayList List = (ArrayList)hqlquery.list();
In hibernate the HQL query positional parameter index starts with 0.
If we do not supply the values to all positional parameters hibernate
display an exception query exception.
We can use alias names as part of HQL query by using a keyword as.
Ex:
String query = from product as p where p.price>? and p.price<?;
We can use order by as part of HQL queries.
Ex:
1
1
eone
Integer
String
Object(2)
2 etwo
2
etwo
Integer
String
Object(2)
A
R
R
A
Y
L
I
S
T
eone
etwo
eone
String
etwo
String
ethree
String
ethree
efour
efour
A
R
R
A
Y
L
I
S
T
String
rs
We can use aggregate functions in HQL queries. The following is an
example using HQL to find number of records available in product table.
String q = select count(*) from product as p;
Query que = hsession.CreateQuery(q);
ArrayList list = (ArrayList)que.List();
Iterator i = list.iterator();
while(i.hasNext()){
Object o = i.next();
Long l = (Long)o;
System.out.println(o);
}
We can join multiple tables and retrieve the records the following is an
example of join tables.
Query HQLquery
Array list = (Arraylist)HQLquery.List();
Iterator := list.iterator();
while(i.hasNext()){
Object o[] = (object[])i.next();
for(int j=0;j<0.length;j++){
Employee e = (Employee) o[0];
Product p = (Product) o[1];
System.out.println(e.getEmployee NO() + \t);
System.out.println(e.getEmployee Name() + \t);
System.out.println(p.getpid() + \t);
System.out.println(p.getName() + \t);
}
}
By using HQL we can perform updating, deletion and insert records into a
database server. To send the update query we use a method executed
update().
Transaction tx = hsession.beginTransaction();
String query = update info.inetsolv.Employee set employee
Address=! Where
employee No = ?;
Query hqlQuery = hsession.createQuery(Query);
hqlQuery.setString(0,xyz);
hqlQuery.setInteger(1,1);
int no = hqlQuery.executeupdate();
System.out.println(no);
tx.commit();
hsession.close();
}
}
Note:
When we perform update, delete and insert operations. We must
place the code in a transaction.
Hql will not support to insert record directly into table. if the data is
already available in table we can copy from one table to another table.
Transaction tx = hsession.beginTransaction();
String
Query
=
insert
into
Employee(employeeNo,employeeName) select pid,
name
from product;
Query hql Query = hsession.createQuery(Query);
int no = hql Query.executeupdate();
System.out.println(no);
tx.commit();
hsession.close();
}
Named positional parameters:
When we write the hql Queries we can use positional
parameters the problem with positional parameters is if somebody trying
to read and understand it takes lot of time. Instead of positional
parameters we use names. This will improve the readability of the
queries.
Named positional parameters will not improve performance separately.
This is because by default named positional parameters also uses
prepare statements. The following is an example of named positional
parameter.
Ex:
From product where price>:min value and price<:max value. The
following is an example of using named positional parameters.
String Query = from product where price>:minvalue and
price<:maxvalue;
Query hql Query = hsession.CreateQuery(Query);
hql Query.setDouble(minvalue,2000);
hql Query.setDouble(maxvalue,6000);
Arraylist list = (Arraylist)hqlQuery.List();
In hibernate to retrieve the data from all the tables we can use hql query
like from java.lang.object
Ex:
Criteria API:
Criteria API is used to retrieve the records from the data base
server the advantage of this API is we are going to represent the queries
in the form of objects.
We can not use Criteria API to insert the record, update the record and
delete the record.
The following is an example of using Criteria API to retrieve the records of
product table.
Ex:
//standard hibernate code
Session hsession = sf.open Session();
Criterial c = hsession.Create Criteria(Product.class);
Arraylist list = (Arraylist)c.list();
Iterator i = list.iterator();
while(i.hasNext()){
Product p = (Product);
next();
System.out.println(p.getPid());
System.out.println(p.getName());
System.out.println(p.getPrice());
}
To work with Criteria API we must follow the following two steps:
1. Represent the Query in the form of Criteria object.
2. Send the Criteria to data base server by using a method list();
Hibernate guys has given predefined classes to add the restrictions. They
are available as part of org.hibernate.criteria package some of the
important classes in that are restrictions,order, property etc.
The following is code to add restrictions to criteria.
Criteria c = hsession.create Criteria(Product.class);
c.add(Restrictions.ge(price,2000d);
c.add(Restrictions.le(price,4000d);
The Restrictions class contains couple of static factory methods. The
internal code of these methods add() the where conditions to the Query
as a developer we are responsible to use these methods based on the
requirements.
To sort the records based on Criteria API they have provided predefined
classes like order. This contains the methods like asc, desc.
Ex:
Criteria c = hsession.Create Criteria(product.class);
c.addOrder(order.desc(price));
To retrieve the specific columns from the data base table we use
projections class.
Ex:
Criteria c = hsession.Create Criteria(product.class);
c.setProjection(Projections.property(name));
When we run the above java program the Array list object contains the
columns corresponding data type.
adding multiple projections:
Criteria c = hsession.Create Criteria(Product.class);
ProjectionList pl = projections.ProjectionList();
Pl.add(Projections.property(name));
Pl.add(Projections.property(pid));
c.setProjection(pl);
Note:
Criteria API is not best sui table for the real time projects and to
develop complicate Queries for example using the functions like di code,
nul1, nul2 etc.
Native SQL API:
The main advantage of Native SQL is we can write data base
specific Queries as part of hibernate. By using Native SQL API we can
perform the operations like insert Query, update, delete, retrieve and call
the procedures and etc.
The following is an example of calling the procedure by using Native SQL.
Ex:
Transaction tx = hsession.beginTransaction();
SQL Query Query = hsession.creteSQLQuery({call myproc});
Query.executeUpadate();
tx.commit();
How do we use hibernate in web based applications:
How do we use hibernate in sturts:
1. Create a web based application.
2. Copy all the hibernate related jar files into project lib folder.
3. Copy hibernate configuration file, POJO classes, hbm files and
hibernate configuration files into classes folder.
4. Create hbm file and servlet to capture data and store data.
Generators:
In all the applications which we developed as of new end user is suppose
to enter the primary key values.
It is not recommended to ask the end user to enter to enter the primary
key values. Its always recommended to generate primary key values by
the application. This resolves the problem of end user remembering the
primary keys.
By using JDBC we have to write code to generate primary key values. If
we use hibernate internally it contains a logic to generate the primary
key values.
Approach1:
In the hbm file we can use generator with hibernate class name or short
name.
<id name = pid type = integer>
<column name = pid/>
<generator class = org.hibernate.id.Assigned/>
</id>
// product.hbm.xml
OR
<id name = pid/>
<column name = pid/>
<generator class = assigned/>
</id>
In the hbm file if we does not supply the generator tag by default
hibernate consider assigned generator.
If we supply a wrong class name or invalid generator class name
hibernate throw an exception could not instantiate id generator.
Increment generator:
When we use this generator it will increment the primary key value
by one based on existing primary key value. This algorithm internally
uses the existing primary key value.
When we use this algorithm it will use the following query to find the
maximum primary key value.
Ex: select max(pid) from product
The following is the configuration of increment generator.
<generator class = org.hibernate.id.Increment Generator>
</generator>
<generator class = Increment>
</generator>
Increment generator can generate the primary key values for short, long,
integer data types only.
We can use increment generator in mysql data base server also.
Identify generator:
This generator can be used only in mysql data base server to use
this generator compulsory the table must be auto increment. The
following is the configuration of identify generator.
<generator class = org.hibernate.id.dentity generator/>
OR
<generator class = identity/>
(sequencehilo):
Seq hilo: This generator uses both sequence as well as hilo value to
generator a primary key value. This is same as hilo generator. this uses
the sequence instead of table. the following is the configuration for
sequence hilo generator.
<generator class = seqhilo>
<param name = sequence>pidseq</param>
<param name = mar_lo>5</param>
</generator>
Uuid/guid: These generators generate the primary key value based on
the IP address of the system and the start up time of JVM and convert it
into 32 bit hexadecimal number and store in data base server.
To work with guid/uuid generators the primary key value data type must
be var char with minimum size of 32 bit. The following is the
configuration of generator.
<generator class = uuid/>
Instead of predefined generator we can use our own generator also to
get the primary key values.
To develop our own generator class it must provide implementation to
interface identifier generator. In this we need to provide the
implementation to generator method.
Ex:
public class OurOwnGenerator implements Identifier Generator{
public serializable generator(SessionImplementor session, object
object){
int eno = 0;
ResultSet
rs
=
session.getbatcher().PrepareBatchStatement(select
max(eno)
from emp).executeQuery();
if(rs.next()){
eno = rs.getInt(1);
eno = eno + 1;
}
return eno;
}
}
To use this generator in hibernate we have to configure it in hbm file as
show below.
Ex: <generator class = info.inetsolv.ourown Generator/>
When we use hibernate in form based applications we have provided the
configure method and build session factory method as part of service
method.
Single ton design pattern:
The main purpose of single ton design pattern is it make sure that
any work execute only once or it make sure that the object is created to
a class only once.
The following Cone class makes sure that it creates only one object for
multiple people.
public class Cone{
private static Cone c;
Static{
System.out.println(creating Cone object only once);
c = new Cone();
}
public static Cone create Cone object(){
return c;
}
Private Cone(){
System.out.println(Cone object is created);
}
}
To get the Cone class object we use a method created Cone object
public class MyApp(){
public static void main(String args[]){
Cone c1 = Cone.create Cone object();
Cone c2 = Cone.create Cone object();
System.out.println(c1);
System.out.println(c2);
}
}
The following is hibernate single ton design pattern. This class make sure
that session factory is created only once.
public class Hibernate SessionFactorySingleTon{
private Static SessionFactory sf = null;
Static{
Configuration cfg = new Configuration();
cfg.configure();
sf = cfg.buildSessionFactory();
}
public Static Session Factory getSessionFactory(){
return sg;
}
private HibernateSessionFactorySingleTon(){
}
}
As part of a servelet we get the session object directly from single ton
design pattern.
Ex: public class StoreProductServlet extends HttpServlet{
public void service(. . . . . . ){
Session hsession = HibernateSession factory single ton .
getSession();
........
......
....
hsession.close();
}
}
The following is an example hibernate temple design pattern. By using
this any body can perform the some operation by using one line.
Ex:
public static void save(object o){
Session hsession = Hibernate session factory.getSession();
hsession.beginTransaction();
hsession.Save(o);
hsession.getTransaction().commit();
Hibernate session factory.close Session();
}
}
Develop a servlet to get a all the records from product table and display
to the client.
Named Queries:
Named Queries will improve the performance of java application.
When we develop a web based application to retrieve the records from
product table and display to the client by using HQL Queries every time it
try to convert HQL Query into corresponding SQl Query. We can improve
the performance of by using named Queries.
Procedure to use Named Queries:
1. Configure Named Queries as part of hbm files.
Ex: <hibernate_mapping>
<class--- >
--------- >
</class>
<query
name
=
gpd>from
info.inetsolv.product</query>
</hibernate_mapping>
//product.hbm.xml
2. From the java application to use the Named Queries use a
method.getNamedQuery()
Query query = hsession.getNamedQuery(gpd);
ArrayList al = (ArrayList)query.list();
Iterator i = list.iterator();
/
Following java application to call the procedure and display to the client.
public class GetRecords{
public static void main(String args[]){
//standard jdbc code
CallableStatement cstmt = con.PrepareCall({call myproc(?)});
cstmt.Execute();
ResultSet rs = (ResultSet) cstmt.getObject(1);
//code to display the records
}
}
Hibernate guys are giving a way to call procedure which takes a
parameter refcursor.
Configure procedure in hbm file as shown below.
<hibernate_mapping>
<class ----- >
---------</class>
<sql_query name = cp callable = true>
<return class = info.inetsolv.product></return>
{call myproc(?)}
</sql_query>
</hibernate_mapping>
To call the procedure from java we use named queries as shown below.
Query query = hession.getNamedQuery(cp);
Arraylist al = (Arraylist)query.list();
Iterator i = al .iterator();
while(i.hasNext()){
product p = (product)i.next();
}
}
We have to follow limitations in hibernate to call the procedure.
1. The first parameter procedure must be out parameter and the data
type must be ref cursor.
2. When we are configuring the procedure in we must use on attribute
callable st.
1
In the java application we get the required Session Factory object and
perform the operations.
Ex: Sun Micro System has released JPA API to interact with data base
servers they are released this API as part of JEE standard API.
The following is the classes and interfaces as part of JPA.
Classes
Interfaces
Persistence
Hibernate guys provided the implementation to JPA API.
Create a java project and add JPA capabilities. There are so many people
who are providing the implementation same of them or top link,
hibernate and open JPA and etc. we can use any jar files to develop JPA
application. When we add JPA capabilities it has created an xml file
whose name is persistence.xml in this we have specified persistence unit
name.
Generate an Entity Beans (POJO classes). Develop a java
application to store the data into employee table.
public class StoreEmp{
public static void main(String args[]){
EntityManagerFactory
emf
=
Persistence.CreateEntityManagerFactory(JPAORACLEP);
EntityManager em = emf.CreateEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Emp e = new Emp();
e.setEno(1);
e.setEno(2);
e.setEno(3);
em.Persist(e);
tx.commit();
em.close();
}
}
The top link provides the implementation of JPA API to work with top link
we are to download the top link jar files and set the class path. When we
are developing a project at the design phase we try to develop two types
of design.
1. Data base design
2. Java design
As part of data base design we will decide the names of the tables and
columns of the tables and etc. At the time of developing the project
developer will not create any tables. In most of the projects we have to
capture multiple address to an employee.
Eno
1
Name Naidu
Address:
Street
Am pet
SR
city
HYD
state
AP
HYD
AP
Name
Street
City
Naidu
Am pet
State
AP
HYD
As part of design we are adding two tables. Emp table and address table
in the Emp table Eno is a primary key. In the address table Eno, Address
no are forming the primary key.
Design 2:
Eno(PK) Name
salary
1
Naidu
Eno
1
Addno Street
City
1
Am pet
State
1
AP
HYD
In the design2 the address table contain Eno, addressno as primary keys.
If more than one column in valued in forming a primary key we call it as
composite primary key. Hibernate will not give the best performance if
the table contains composite primary key. Hibernate give the best
performance if its having only one primary key.
Design 3: In this design we have two tables. They are emp and address.
In the address table we will try to have a new column which acts as
primary key.
Eno(PK) Name
salary
1
Naidu
100000
Aid
Eno(PK) addno
City
1
1
Street
State
1
APet
HYD
AP
2
2
1
APet
HYD
Generally by using hibernate we should be able to create the tables. but
according to the project design first we are creating tables from the
tables we are creating POJO classes. Creating the POJO classes from the
table is called as hibernate reverse engineering.
There are some situations where we need to develop hibernate
applications based on legacy data base servers.
**What are legacy data base servers?
The data base server which uses composite primary keys is called as
legacy data base servers. Procedure to develop hibernate applications
based on legacy data base. Create the following the two tables.
Table 1: create table emp(eno number(5) primary key,
Name varchar2(20), salary number(10,2);
1
String city;
String state;
//provide setters and getters }
We are generated two hbm files. They are:
1. Emp.hbm.xml
2. Address.hbm.xml
We have not observed any changes in Emp.hbm.xml files. We have
observed lot of changes in address.hbm.xml file with respect to
composite primary key.
<hibernate_mapping>
<class name = info.inetsolv.Address table = Address>
<composite-id name = id class = info.inetsolv.AddressId>
<key-property name Eno>
<column name = Eno/>
</key-property>
<key-property name = addno>
<column name = Addno/>
</key-property></composite-id>
<property name = street/>
<property name = city/><property name = state/>
</class>
<hibernate_mapping>
The following java application to store the data into data base server
creating the emp obj.
1. AddressId obj
2. Address obj
3. Call save method for emp.address
To establish the relationship between tables we do it based on the data
available in the tables. They are:
1.
2.
3.
4.
One to many
Many to one
One to one
Many to many
number(5),
Name
varchar2(20),
salary
String name;
emp(Eno);
Double salary;
Sent address = new HashSet(0);
//provide setting and getters
}
The following is the configuration of the Emp.hbm.xml represents the
many relationship.
<hibernate_mapping>
<class name = info.inetsolv.Emp>
<id name = Eno/>
<property name = name/>
<property name = salary/>
<set name = address inverse = true>
<key>
<column name = ENO/>
</key>
<one-to-many class = info.inetsolv.Address/>
</set>
</class>
<hibernate_mapping>
The following is the POJO class for Address table.
public class Address{
Integer aid;
1
Emp emp;
Integer addno;
String street;
String city;
String state;
// provide settress and gettress
}
The following hbm file for address table.
<hibernate_mapping>
<class name = info.inetsolv.Address>
<id name = aid/>
<many-to-one name = EMP class = info.inetsolv.Emp>
<column name = ENO/>
</many-to-one>
<property name = addrno/>
<property name = street/>
<property name = city/>
<property name = state/>
</class>
</hibernate_mapping>
Generally IDE recognize the relationship between tables and generate
hbm files and POJO classes. Hibernate understand the relationship
between the tables based on the tags which are available in hbm file. To
Eno = null
Name = null
Salary =
null
Address
one
Emp
Emp
aid = null
aAddrno =
null
city = null
state =
null
Address
Size =
1
Hashtable
The following java application to store the data into emp as well as
address table.
public class store{
public static void main(String str[]){
Session h = HibernateSessionFactory.getSession();
Transaction tx = h.beginTransaction();
Emp e = new Emp();
e.SetEno(1);
e.SetName(Naidu);
e.SetSalary(10,000);
1
When we call save(e) hibernate can find the relationship between the
tables and store the data into dependent on tables to do this we must
specify two attributes inverse and cas code.
<Set ----------- inverse = true cascade = all/>
Develop a java application to retrieve the data from emp table who emp
no is 2 (we would like to retrieve the corresponding address details).
Hibernate checks two strategies to retrieve the record from data base
server.
1. Lazy loading ------>
Aggrisive (eager) loading.
**What is lazy loading?
When ever we perform can operation on one table and table has
relationship with other tables and then we called a load method it will
retrieve the data from that table only.
Hibernate retrieve the records from child table when even any operation
is carried out of any other table. By default hibernate uses lazy
loading(true).
**What is Aggressive loading?
When ever we call a load method on a parent table it will try to retrieve
record form child table also even though user doesnt access any
properties. How to make hibernate as aggressive we have to configure
lazy = false in hbm file of parent table.
Order table
many-to-one: We would like to maintain the tables for multiple
employees we would like to have departments and there are
departments with out employees to achieve we use many-to-one
relationship.
Eno(pk) name
Did(fk)
Emp
Did(pk)
name Dept
one-to-one relationship:
We would like to maintain one-to-one relationship
between team and captain tables. The following are two takes which we
are using to achieve this.
Tid(pk)
location
name
Team
Tid(pk)
(pk)
Cname
Captain
Note:
When we create the above two tables and establish the
relationships and generate hbm files and POJO classes IDE as unnecessarily created one-to-many relationship this is because of adding a
foreign key relationship between captain and team table.
1. Create two tables team and captain with only primary key do not
add the foreign in the beginning this is because if we had a foreign
key IDE will generate one-to-many relationship.
2. Generate hbm files and POJO classes.
<hibernate-mapping>
<class . . . . >
.........
<one-to-one name = captain class = info.inetsolv.captain
cascade = all>
</one-to-one>
</class>
</hibernate-mapping> //team.hbm.xml
Similar to team POJO class and hbm file, develop captain java and
captain.hbm.xml
*Develop the hibernate application to store data in to data base server.
public class StoreTeamDetails{
public static void main(String[] args){
Session hsession = HibernateSessionFactory.getSession();
Transaction tx = hsession.beginTransactions();
Team t = new Team();
t.setTid(tid);
t.setName(teamName);
t.setLocation(location);
Captain c = new Captain();
c.setTid(tid);
c.setName(captain);
c.setTeam(t);
t.setCaption(c);
hsession.save(c);
tx.commit();
HibenateSessionFactory.closeSession();
}
}
many-to-many:
We would like to implement many-to-many relationship b/w student
and course tables.
Sid(pk)
Sname
Cid(pk)
Cname
//student
//student-course
Sid(pk)
Cid(pk)
//course
tx.commit();
HibenateSessionFactory.closeSession();
}
}