Hibernate Notes
Hibernate Notes
HIBERNATE
COURSE MATERIAL
BY
NAGOOR BABU
1
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Index
1. Course Content………………………………………………………………….….Page 04
2. Introduction………………………………………………………………….….…...Page 06
3. Steps to prepare First Hibernate Application…………………………….....….. Page 20
4. Hibernate Applications with Eclipse……………………………………….......... Page 31
5. Hibernate Applications…………………………………………….........................Page 37
6. Hibernate Persistence Object Lifecycle……………………………………........ Page 118
7. Hibernate Schema Generation Tools…………………………………............... Page 121
8. Creating SessionFactory object in Hibernate4.x version……………….......… Page 128
9. Primary Key Generation Algorithms in Hibernate……………….………....….. Page 132
10. Transaction Management………………………………………………......…....Page 148
11. Connection Pooling in Hibernate……………………………………..……........Page 157
12. Bulk Operations………………………………………………………...….....…...Page 178
13. Hibernate Filters……………………………………………..….…………....…...Page 249
14. Hibernate Mappings……………………………...………………………..…......Page 254
..
3
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Introduction
Enterprise
Enterprise Application
Data Persistency
Data Persistency through Serialization and Deserialization
Data Persistency through JDBC
Data Persistency through ORM
Hibernate History
Hibernate Features
Hibernate Architecture
4. Hibernate Applications
Example On Hibernate SaveOrUpdate(--) method
Example to delete records from DB
Example To retrieve Record from DB
HIBERNATE with My SQL Database
AWT/GUI-Hibernate Integration Application:
Servlet_Hibernate_Application
JSP_Hibernate_Application
Struts_Hibernate Integration
Integration Of Hibernate with Struts
Ditached State
Page
Removed State
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HIBERNATE
Introduction
Enterprise: It is a Business Organization or a Group of Organizations running under Single
label.
It is a top most layer in enterprise applications, it will improve Look and Feel to the
enterprise applications.
It will provide starting point to the users in order to interact with enterprise application.
It will provide very good environment to get data from users in order to execute enterprise
applications.
It will provide very good environment to perform client side data validations by executing
Java script functions.
To prepare this layer we will use a separate logic called as "Presentation Logic".
In enterprise applications, to prepare Presentation Logic we will use the technologies like
AWT, SWING, Java FX, Html, JSP, Java Script, Velocity, Freemarker,....
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Data Persistency:
To achieve Data Persistency in database applications we will use a set of Operations [CRUD]
called as Date Persistence Operations".
To achieve Data Persistency in Enterprise Applications we will use a set of tech called as "Data
Persistency Tech".
To achieve Data Persistency in enterprise applications we will use the following technologies w.r.t
JAVA.
3) ORM Implementations
Page
a) Hibernate
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To perform Serialization and Deserialization JAVA has provided the following two byte oriented
streams
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
oos.writeObject(emp1);
In Serialization and Deserialization Data Persistency mechanism, we will store data in file
system ,where file system is providing permanent storage for our data, so that, Serialization
and Deserialization is a Data Persistency Mechanism.
In Serialization and Deserialization data persistency mechanism, we will use a flat file to
store data, it is platform dependent, it is not suitable for the platform independent front end
technologies like JAVA, .NET,....
In Serialization and Deserialization Data Persistency mechanism, we will use two byte
oriented streams like ObjectOutputStream and ObjectInputStream to perform Serialization
and Deserialization, so that, this data persistency mechanism is suitable for only byte
oriented data.
In this data persistency mechanism, we are using file system to store data , it able to store
less data , it able to provide less security and it able to increase data redundancy, it is not
9
suggestible in applications.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In this data persistency mechanism, query language support is not existed so that database
operations are very much difficult.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In JDBC Applications, the steps like Load and Register Driver, Establish Connection ,
Create Statement and Close resources ... are common ion every JDBC Application, we
must write repeatedly, it will increase Code duplication .
In Jdbc applications, we have to hardcode the JDBC Parameters like Driver class name,
Driver URL, Database User Name and Databse password,...
In JDBC almost all the exceptions are checked exceptions, we must handle them by
11
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Paradigm Mismatches:
In enterprise applications both the data models are having their own approaches to represent data
in effective manner, these differences are able to provide Paradigm Mismatches, and these
mismatches are able to reduce data persistency in enterprise applications.
In general, Object Oriented Data Model and Relational data model are having the following
mismatches.
In general, Object Oriented Data Model and Relational data model are having the following
mismatches.
In general, Object Oriented Data Model and Relational data model are having the following
mismatches.
In general, Object Oriented Data Model and Relational data model are having the following
mismatches.
1. Granularity Mismatch
12
3. Associations Mismatch
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Granularity Mismatch:
In general, Granualarity is representing a count .
EX: In a database no of tables , in a table no of columns, In a class no of properties, in an
application no of classes,.....
IN Enterprise applications, we are able to represent an User in Object Oriented Data Model
in one approach and in Relational data Model in another approach.
In Object oriented Data model we may take a class User with the properties uname, uage
,... to represent an User , here if we want to represent address details of an user then we
will take a seperate class Address with the properties like pno, street, city,.... and we will
declare Address class reference variable in User class.
In Relational data Model, we may represent a User entity and its address details in the form
of a single table or in the form of multiple tables with primary key and foreign key
relationship.
In the above context, the no of classes [Granularity] in Object Oriented Data Model and the no of
tables [Granularity] in Relational data model may not be matched, it may reduce data persistency
in enterprise applications, in this context, to improve Data persistency we have to use ORM
implementations like Hibernate.
For the above Granularity mismatch, Hibernate has provided a solution in the form of
"Component Mapping".
13
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Object Oriented Data Model we are able to use inheritance inorder to improve Code
Reusability. In Java applications, we are able to represent inheritance by using "extends"
keyword.
In Relational data Model, we are not having any feature to represent inheritance between
tables, in Relational Data model we are able to achieve inheritance kind of feature by using
either of the following approaches.
1. We may take single table to represent all the properties of the classes which are included
in inheritance.
2. We may take a seperate table for each and every sub class with the super class
properties and sub class properties.
3. We may take a seperate table for super class and for sub classes with Primary Key and
Foreign Key relationships.
In the aboce context, Object Oriented Data Model is having its own representation to
achieve INheritance and relational Data Model is having its own approaches to represent
Inheritance kind of feature, this difference is representing "Inheritance Mismatch", It may
reduce data persistency in enterprise applications.
In the above context, to improve Data Persistency we have to resolve Inheritance Mismatch
problem, for this, we have to use ORM implementations like Hibernate.
For the above Inheritance Mismatch, Hibernate has provided the following three types of
solutions.
1. Table Per Class Hierarchy.
2. Table Per Sub class
3. Table Per Concrete Class
14
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Object Oriented data Model, we are able to implement associations by declaring either
single reference variable or array or collection of reference variables of a class in another
class.
In Relational Data Model , we are able to achieve associationes between entities either by
defining Primary-Key and Foreign-Key relationships between entity tables or by using join
columns or by using join tables between entity tables.
In the above context, Object Oriented Data Model and Relational data Model both are
having their own apporoaches to implement Associations, this difference in their
approaches may create mismatch between these two data models, it may reduce Data
Persistency in enterprise applications.
15
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Object Oriented model, we are able to represent all the entities in the form of classes.
In Object Oriented model, we are able to prepare no.of instances from a particular class.
In the above context, it is possible to check whether the two objects are identical or not by
using either == operator or .equals ( ) method from object class.
In case of relational model, all the records in the entity tables be identical if we use
primary key column.so that no specific mechanism is existed to check whether the two
records are identical or not.
If we consider the above two data models. There is a mismatch about identity checking, it
will make data persistency is compel.
In the above context, to simplify data we have to use ORM implementations. With respect
to java technology.
ORM is a set of rules and regulations or a set guidelines to provide mapping between
Object Oriented Programming elements like classes, id properties, normal properties and
the relational data model elements like table, primary key columns, and normal columns
either by using XML file or by using Annotations.
Examples:
1. EJB’S
2. HIBERNATE
3. JPA
4. TOPLINK
5. OPEN JPE
2. EJB Vs HIBERNATE:
i. In case of EJB’S entity beans, we should require 1-1 relation b/w database table and the
entity classes. But it is not mandatory in case of hibernate.in case of hibernate, a single
entity class may represent multiple no.of tables and single table may represent multiple
16
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. JPA Vs HIBERNATE:
Hibernate is a product, it has implemented ORM rules and regulations as per JPA
guidelines in order to provide data Persistency in enterprise applications.
Hibernate History:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Hibernate Architecture:
18
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Hibernate Configuration File will provide all the configuration details like driver class name, driver
URL, Database User name , Database password,.... which we required to establish connection
with database and to setup JDBC environment.
Hibernate Mapping file will provide all the mapping details like Bean Class name and Database
table name, ID property and Primary key column , Normal Properties and Normal Columns,....
1) Client Application will perform the following three actions in Hibernate applications mainly.
2) Activating Hibernate Software, in this case, Hibernate Software will take all configuration
details from hibernate configuration file and Hibernate Software will set up the required
JDBC Environment to perform database operations.
When Client Application perform persistence operation, Hibernate Software will perform the
following actions.
1) Hibernate Software will take persistence method call and identify persistence Object.
2) Hibernate Software will take all mapping details from hibernate mapping file like database
table name and all column names on the basis of Persistence object.
3) Hibernate Software will prepare database dependent sql query on the basis of table
names and column names and with the persistence object provided data.
4) Hibernate Software will execute the generated database dependent sql query and perform
the required persistence operation.
19
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: To run Hibernate Applications we have to download all Hibernate JAR file and we have to
them for our Hibernate application.
In Hibernate applications, to prepare Persistence classes we have to use the following Guidelines
1) In Hibernate applications Persistence classes must be POJO classes [Plain Old Java
Object], they must not extend or implement predefined Library.
2) In hibernate Applications Persistence classes must be public, Non abstract and non-final.
Where the main intention to declare persistence classes as public is to bring persistence
classes scope to Hibernate software in order to create objects.
Where the main intention to declare persistence classes as Non abstract is to allow to
create Objects for Persistence classes
Where the main intention to declare persistence classes as Non final is to allow to extend
one persistence class to another persistence class as per the requirement.
3) In Persistence classes all Properties must be declared as per database table provided
columns, where names are not required to be matched, but, data types must be
compatible.
4) In Persistence classes, all properties must be declared as private in order to improve
Encapsulation.
5) In Persistence classes , we must define a separate set of setXXX () and getXXX ()
methods for each and every property
6) In persistence classes, we must declare all methods are public.
20
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: Employee.java
24. }
25. public float getEsal(){
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of mapping file in Hibernate applications is to provide mapping between a class
,id property and normal properties from Object Oriented Data Model and a table, primary key
column and normal columns from Relational data model.
In Hibernate applications, mapping file is able to provide the mapping details like Basic OR
mapping, Component mapping, inheritance mapping, Collections mapping, Associations mapping,
To prepare mapping file in Hibernate applications we have to provide mapping file name with the
following format.
POJO_Class_Name.hbm.xml
The above format is not mandatory, we can use any name but we must provide that intemation to
the hibernate software.
In Hibernate applications, we can provide any no of POJO classes, w.r.t each and every POJO
class we can define a separate mapping file.
Note: In Hibernate applications, it is possible to configure more than POJO class in single
mapping file.
Upto Hibernate3.2.5 version Hibernate Mapping file is mandatory to provide mapping details, but,
right from Hibernate3.2.5 version mapping file is optional, because, Hibernate 3.2.5 version has
provided annotations as an alternative to mapping file.
To provide Basic mapping between POJO class and table in mapping file we have to use the
following XML tags provided by Hibernate.
1. <!DOCTYPE......>
2. <hibernate-mapping>
22
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where <hibernate-mapping> tag is root tag in mapping file, it will include no of classes
configuration.
Where <class> tag is able to provide single POJO class configuration inorder to provide
mapping between POJO class name and the respective table name.
Where "name" attribute in <class> tag is able to provide fully qualified name of the POJO
class.
Where "table" attribute in <class> tag is able to provide the respective table name.
Where <id> tag is able to provide ID property configuration inorder to provide mapping
between ID property and the respective primary key column.
Where "name" attribute in <id> tag is able to provide id property name of the POJO class.
Where "column" attribute in <id> tag is able to provide primiry key column defined in table.
Where <property> tag is able to provide normal bean property configuration inorder to
provide mapping between normal bean property and normal table column.
Where "name" attribute and "column" attribute will take bean property name and table
column name respectively.
Note: If bean property names and table column names are same then it is optional to provide
"column" attribute in mapping file.
EX:
1. <!DOCTYPE.....>
2. <hibernate-mapping>
3. <class name="com.durgasoft.Employee" table="emp1">
4. <id name="eno" column="eno"/>
5. <property name="ename"/>
6. <property name="esal" column="emp_Sal"/>
23
9. </hibernate-mapping>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main purpose of hibernate configuration file is to provide all configuration details of hibernate
application which includes Jdbc parameters to prepare connection , Transactions configurations,
Cache mechanisms configurations, Connection pooling configurations,........
In Hibernate applications, we are able to provide more than one configuration file , but, for each
and every database, that is, in hibernate applications if we use multiple databases then we are
able to prepare multiple configuration files.
To prepare hibernate configuration file with basic configuration details we have to use the
following XML tags.
1. <!DOCTYPE....>
2. <hibernate-configuration>
3. <session-factory>
4. <property name="--"> value </property>
5. ------
6. ------
7. <mapping resource="---"/>
8. -----
9. </session-factory>
10. </hibernate-configuration>
EX:
hibernate.cfg.xml:
24
1. <!DOCTYPE....>
Page
2. <hibernate-configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: org.hibernate.dialect.Oracle9Dialect
org.hibernate.dialect.Oracle10gDialect
org.hibernate.dialect.MySQLDialect
The main intention of Hibernate Client application is to activate Hibernate Software, creating
persistence objects and performing Persistence operations.
To prepare Client Application in hibernate applications we have to use the following steps as per
Hiberante3.x version.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate, the main intention of Configuration object is to store all the configuration details
which we provided in hibernate configuration file.
To represent Configuration object Hibernate has provided a predefined class in the form of
"org.hiberante.cfg.Configuration".
To create Configuration class object we have to use the following constructor from Configuration
class.
public Configuration()
EX: Configuration cfg = new Configuration();
If we use the above instruction in Hibernate applications then we are able to get an empty
Configuration object in heap memory, it will not include any Configuration details.
If we want to store Configuration details from Configuration file we have to use either of the
following methods.
When we use configure() method then Hibernate Software will search for hibernate.cfg.xml file, if it
is available then Hibernate software will load the content of hibernate.cfg.xml file, parse it and
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate, the main intention of Session Factory object is to manage Connections, Statements,
Cache levels, .... and it able to provide no of Hibernate Session objects.
To represent Session Factory object Hibernate has provided a predefined interface in the form of
"org.hibernate.Session Factory".
To get Session Factory object we have to use the following method from Configuration class.
Note: The above approach to get Session Factory object is available upto Hibernate3.x version,
buildSessionFactory() was deprecated in Hibernate4.x version.
Session Factory object is heavy weight and it is thread safe upto a particular Database, because,
it able to allow more than one thread at a time.
In Hibernate, for each and every database interaction a separate Session will be created.
To represent Session object, Hibernate has provided a predefined interface in the form of
"org.hibernate.Session".
To get Session object, we have to use the following method from Session Factory.
In Hibernate, Session object is light weight and it is not thread safe, because, for each and every
27
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Transaction is a unit of work performed by Front End applications on Back end systems.
It will return Transaction object with out begin, where to begin Transaction we have to use the
following method.
In Hibernate applications, after performing persistence operations we must perform either commit
or rollback operations inorder to complete Transactions, for this, we have to use the following
methods from Transaction.
Note: In Hibernate applications, Transaction is required for only Non Select operations, not
required for Select operations.
In Hibernate applications, to perform persistence operations Session has provided the following
methods.
To insert an object or record into Database table we have to use the following methods.
1. save(--)
2. persist(--)
28
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Ans:
In Hibernate applications, save() method can be used to insert a record into the Database table
and it will retuen Primary Key value of the inserted record.
In Hibernate applications, persist() method can be used to insert a record into database table and
it will not return any value.
To update a record ion database table we have to use the following methods.
1. update(--)
2. saveOrUpdate(--)
Ans:
Where update(-) method will perform updation on a record in database table if the specified record
is existed otherwise it will rise an Exception.
Where saveOrUpdate(-) method will insert the specified record in database table if the specified
record is not existed . If the specified record is existed in database table then it will update the
record.
To delete a record from database table we have to use the following method.
To retrive a record from database table we have to use the following methods.
29
1.get(--)
2.load(--)
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Ans:
1. get() method can be used to retrive a record from database table if the record is existed. If the
required record is not existed then get() method will return null value.
load() method can be used to retgrive a record from database table if the record is existed. If the
required record is not existed then load() method will rise an Exception like HibernateException.
2. get() method is able to perform eager or early loading, that is, it will interact with database
directly and it will retrive data and return to Hibernate application in the form of Object on the
method call.
load() method will perform Lazy or late Loading , that is, when we access load() method then a
duplicate object will be created with the primary key value without interacting with database. When
we use other properties of the Object then only it will fetch data from database table and return
that data to Java application.
In Hibernate applications, it is convention to close Session and Sessionfactory objects at the end
of client application in order to avoid security problems.
30
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Installation Process:
1. download eclipse-jee-oxygen-1a-win32.zip
2. extract eclipse-jee-oxygen-1a-win32.zip file at the required location.
3. After step 2 , we will find "eclipse" folder ie installation folder.
4. Double click on eclipse icon available at c:\eclipse\ location.
5. After step4, we will get a window to select workspace, where specify the location where
we want to manage all the applications.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft;
2. public class Employee{
3. private int eno;
4. private String ename;
5. private float esal;
6. setXXX() and getXXX()
7. }
3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4. <hibernate-mapping>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
11. </property>
12. <property name="connection.user">system</property>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.cfg.Configuration;
7.
8. import com.durgasoft.hbn.pojo.Employee;
9.
10. public class ClientApp {
11.
12. public static void main(String[] args)throws Exception {
13. Configuration cfg = new Configuration();
14. cfg.configure("/com/durgasoft/hbn/cfgs/hibernate.cfg.xml");
15. SessionFactory session_Factory = cfg.buildSessionFactory();
16. Session session = session_Factory.openSession();
17. Transaction tx = session.beginTransaction();
18. Employee emp = new Employee();
19. emp.setEno(111);
20. emp.setEname("AAA");
35
21. emp.setEsal(5000);
22. emp.setEaddr("Hyd");
Page
23. session.save(emp);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
36
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.hbn.pojo;
2. public class Employee {
3. private int eno;
4. private String ename;
5. private float esal;
6. private String eaddr;
7. setXXX() and getXXX()
8. }
Employee.hbm.xml
hibernate.cfg.xml
1. <!DOCTYPE...>
2. <hibernate-configuration>
3. <session-factory>
4. <property name="connection.driver_Class"> oracle.jdbc.OracleDriver</prope
rty>
5. <property name="connection.url"> jdbc:oracle:thin:@localhost:1521:xe</prope
37
rty>
Page
6. <property name="connection.username">system</property>
7. <property name="connection.password">durga</property>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. package com.durgasoft.hbn.test;
2. import org.hibernate.*;
3. import org.hibernate.cfg.Configuration;
4. import com.durgasoft.hbn.pojo.Employee;
5. public class ClientApp {
6. public static void main(String[] args)throws Exception {
7. Configuration cfg = new Configuration();
8. cfg.configure("/com/durgasoft/hbn/cfgs/hibernate.cfg.xml");
9. SessionFactory session_Factory = cfg.buildSessionFactory();
10. Session session = session_Factory.openSession();
11. Transaction tx = session.beginTransaction();
12. Employee emp = new Employee();
13. emp.setEno(111);
14. emp.setEname("AAA");
15. emp.setEsal(5000);
16. emp.setEaddr("Hyd");
17. session.save(emp);
18. tx.commit();
19. System.out.println("Employee Record inserted Succesfully");
20. session.close();
21. session_Factory.close();
22. }
23. }
In Hibernate Applications, when we access persistence methods , Hibernate Software will take
that persistence method call and it will prepare databse dependent native sql query on the basis of
hibername mapping details and configuration details . In this context, to display the generated
database dependent sql query on console we have to use "show_sql" property with the value
"true" in hibernate configuration file.
38
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.hbn.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. this.esal = esal;
26. }
27. public String getEaddr() {
28. return eaddr;
29. }
30. public void setEaddr(String eaddr) {
31. this.eaddr = eaddr;
32. }
33.
34. }
39
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
ClientApp.java
1. package com.durgasoft.hbn.test;
40
2.
3. import org.hibernate.Session;
Page
4. import org.hibernate.SessionFactory;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.hbn.pojo;
41
2.
3. public class Employee {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
8. <property name="ename"/>
9. <property name="esal"/>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.cfg.Configuration;
7.
8. import com.durgasoft.hbn.pojo.Employee;
9.
10. public class ClientApp {
11.
12. public static void main(String[] args) {
13. SessionFactory session_Factory = null;
14. Session session = null;
15. try {
16. Configuration cfg = new Configuration();
17. cfg.configure("/com/durgasoft/hbn/cfgs/hibernate.cfg.xml");
43
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.hbn.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
44
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
hibernate.cfg.xml
6. <session-factory>
7. <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
Page
8. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.cfg.Configuration;
6.
7. import com.durgasoft.hbn.pojo.Employee;
8.
9. public class ClientApp {
10.
11. public static void main(String[] args) {
12. SessionFactory session_Factory = null;
13. Session session = null;
14.
15. try {
16. Configuration cfg = new Configuration();
17. cfg.configure("/com/durgasoft/hbn/cfgs/hibernate.cfg.xml");
18. session_Factory = cfg.buildSessionFactory();
19. session = session_Factory.openSession();
20. Employee emp = (Employee)session.get("com.durgasoft.hbn.pojo.Employee",222 );
30. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. class HibernateUtil{
2. private static SessionFactory sessionfactory;
3. static{
4. try{
5. Configuration cfg = new Configuration();
47
6. cfg.configure(---);
7. sessionFactory = cfg.buildSessionFactory();
Page
8. }catch(Exception e){
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Employee.java
1. package com.durgasoft.hbn.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
48
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
hibernate.cfg.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.hbn.util;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.cfg.Configuration;
6.
7. public class HibernateUtil {
8. private static SessionFactory sessionFactory;
9. static {
10. try {
11. Configuration cfg = new Configuration();
12. cfg.configure("/com/durgasoft/hbn/cfgs/hibernate.cfg.xml");
13. sessionFactory = cfg.buildSessionFactory();
14. } catch (Exception e) {
15. e.printStackTrace();
16. }
17. }
18.
19. public static SessionFactory getSessionFactory() {
20. return sessionFactory;
21. }
22. public static void cleanUp(SessionFactory sessionFactory, Session session) {
23. session.close();
24. sessionFactory.close();
25. }
26. }
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5.
6. import com.durgasoft.hbn.pojo.Employee;
7. import com.durgasoft.hbn.util.HibernateUtil;
8.
9. public class ClientApp {
50
10.
11. public static void main(String[] args) {
Page
12. try {
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
51
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.hbn.pojo;
2.
3. public class Student {
4. private String sid;
5. private String sname;
6. private String saddr;
7.
8. public String getSid() {
9. return sid;
10. }
11. public void setSid(String sid) {
12. this.sid = sid;
13. }
14. public String getSname() {
15. return sname;
16. }
17. public void setSname(String sname) {
18. this.sname = sname;
19. }
20. public String getSaddr() {
21. return saddr;
22. }
23. public void setSaddr(String saddr) {
24. this.saddr = saddr;
25. }
26.
27.
28. }
Student.hbm.xml
8. <property name="sname"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
HibernateUtil.java
1. package com.durgasoft.hbn.util;
2.
3. import org.hibernate.SessionFactory;
4. import org.hibernate.cfg.Configuration;
5.
6. public class HibernateUtil {
7. private static SessionFactory sessionFactory;
8. static {
9. try {
10. Configuration cfg = new Configuration();
11. cfg.configure("/com/durgasoft/hbn/cfgs/hibernate.cfg.xml");
12. sessionFactory = cfg.buildSessionFactory();
13. } catch (Exception e) {
53
14. e.printStackTrace();
15. }
Page
16. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentService.java
1. package com.durgasoft.service;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5.
6. import com.durgasoft.hbn.pojo.Student;
7. import com.durgasoft.hbn.util.HibernateUtil;
8.
9. public class StudentService {
10. Student std = null;
11. public Student search(String sid) {
12. try {
13. SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
14. Session session = sessionFactory.openSession();
15. std = (Student) session.get("com.durgasoft.hbn.pojo.Student", sid);
16. } catch (Exception e) {
17. e.printStackTrace();
18. }
19. return std;
20. }
21. }
SearchFrame.java
1. package com.durgasoft.client;
2.
3. import java.awt.Button;
4. import java.awt.Color;
5. import java.awt.FlowLayout;
6. import java.awt.Font;
54
7. import java.awt.Frame;
8. import java.awt.Graphics;
Page
9. import java.awt.Label;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
50. this.add(b);
51. }
Page
52. @Override
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. package com.durgasoft.client;
2.
3. public class ClientApp {
4.
5. public static void main(String[] args) {
6. SearchFrame searchFrame = new SearchFrame();
7.
8. }
9. } 56
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
loginform.html
16. <tr>
Page
17. <td>Password</td>
18. <td><input type="password" name="upwd"/></td>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
success.html
failure.html
3. <head>
4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
User.hbm.xml
4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HibernateUtil.java
1. package com.durgasoft.hbn.util;
2.
3. import org.hibernate.SessionFactory;
4. import org.hibernate.cfg.Configuration;
5.
6. public class HibernateUtil {
7. private static SessionFactory sessionFactory;
8. static {
9. try {
10. Configuration cfg = new Configuration();
11. cfg.configure("/com/durgasoft/hbn/cfgs/hibernate.cfg.xml");
12. sessionFactory = cfg.buildSessionFactory();
13. System.out.println(sessionFactory);
14. } catch (Exception e) {
15. e.printStackTrace();
16. }
17. }
18. public static SessionFactory getSessionFactory() {
19. return sessionFactory;
20. }
21. }
User.java
1. package com.durgasoft.hbn.pojo;
2.
3. public class User {
4. private String uname;
60
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
UserService.java
1. package com.durgasoft.service;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5.
6. import com.durgasoft.hbn.pojo.User;
7. import com.durgasoft.hbn.util.HibernateUtil;
8.
9. public class UserService {
10. String status = "";
11. public String checkLogin(String uname, String upwd) {
12. try {
13. SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
14. Session session = sessionFactory.openSession();
15. System.out.println(session);
16. User user = (User)session.get(com.durgasoft.hbn.pojo.User.class, uname);
17. if(user == null) {
18. status = "failure";
19. }else {
20. if(user.getUpwd().equals(upwd)) {
21. status = "success";
22. }else {
61
25. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
LoginServlet.java
1. package com.durgasoft.servlets;
2.
3. import java.io.IOException;
4.
5. import javax.servlet.RequestDispatcher;
6. import javax.servlet.ServletException;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10.
11. import com.durgasoft.hbn.util.HibernateUtil;
12. import com.durgasoft.service.UserService;
13. public class LoginServlet extends HttpServlet {
14. public void init() {
15. HibernateUtil.getSessionFactory();
16. System.out.println("init()");
17. }
18. private static final long serialVersionUID = 1L;
19. protected void doPost(HttpServletRequest request, HttpServletResponse response) thr
ows ServletException, IOException {
20. String uname = request.getParameter("uname");
21. String upwd = request.getParameter("upwd");
22.
23. UserService user_Service = new UserService();
24. String status = user_Service.checkLogin(uname, upwd);
25.
26. RequestDispatcher requestDispatcher = null;
27. if(status.equals("success")) {
28. requestDispatcher = request.getRequestDispatcher("/success.html");
62
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
searchform.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>Customer Search Form</h3>
10. <form method="POST" action="./search.jsp">
11. <table>
12. <tr>
13. <td>Customer ID</td>
14. <td><input type="text" name="cid"/></td>
64
15. </tr>
Page
16. <tr>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
notexisted.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>Customer Search Status</h3>
10. <font color="red" size="6">
11. <b>
12. Customer Not Existed
13. </b>
14. </font>
15. <h3>
16. <a href="./searchform.html">|Customer Search Form|</a>
17. </h3>
18. </body>
19. </html>
display.jsp
1. <%@page import="com.durgasoft.hbn.pojo.Customer"%>
2. <%!
3. Customer customer = null;
4. %>
5. <%
65
6. customer = (Customer)request.getAttribute("customer");
7. %>
Page
8. <html>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
search.jsp
1. <%@page import="com.durgasoft.hbn.pojo.Customer"%>
2. <%@page import="org.hibernate.Session"%>
3. <%@page import="org.hibernate.SessionFactory"%>
4. <%@page import="org.hibernate.cfg.Configuration"%>
5. <%!
66
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Customer.java
1. package com.durgasoft.hbn.pojo;
2.
3. public class Customer {
4. private String cid;
5. private String cname;
6. private String caddr;
7. private String cemail;
8. private String cmobile;
9.
10. public String getCid() {
11. return cid;
67
12. }
13. public void setCid(String cid) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Customer.hbm.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
web.xml
12. </web-app>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Struts Overview:
Ans:
Web Frameworks will provide very good environment to prepare and execute web applications
only.
EX: Struts, JSF.
Application Frameworks will provide very good environment to prepare and execute any type of
JAVA/J2EE Applications including Standalone Applications, Web applications, Distributed
Applications,
EX: Spring
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to prepare Struts applications in Struts1.x version then we have to use the following
components
1. View
2. Deployment Descriptor
3. Controller [ActionServlet]
4. Action class
5. Action Form
6. Struts Configuration File
1. View:
This type view part is able to provide only information to the user, which includes status of the
server side actions like Success, failure, ... and display a particular database table data,.....
EXAMPLE: success.html
This type of view part is able to provide a form to collect data from users and to submit data to the
server side applications.
In Struts applications, to prepare Presentation part we are able to use plain HTML tags, but, which
are not suggestible. In Struts applications it is suggestible to use Struts provided tag library.
EX: loginform.html
71
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The above login form with Struts provided html tag library
EX: loginform.jsp
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Deployment descriptor is web.xml file, it will provide description about our web application which is
required by the container in order to perform server side actions.
In general, in web applications, web.xml file will provide the following configuration details.
In Struts based web applications, the main intention of web.xml file is to configure controller
Servlet that is ActionServlet.
EX:
1. <web-app>
2. <servlet>
3. <servlet-name>actionServlet</servlet-name>
4. <servlet-class>org.apache.struts.action.ActionServlet
5. </servlet-class>
6. <load-on-startup>1</load-on-startup>
7. </servlet>
8. <servlet-mapping>
9. <servlet-name>actionServlet</servlet-name>
10. <url-pattern>*.do</url-pattern>
11. </servlet-mapping>
12. </web-app>
3. Controller [ActionServlet]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: In Struts applications, ActionServlet is performing all the above actions by using
"RequestProcessor" internally.
In Struts based web applications, the main intention of ActionForm or FormBean component is to
manage a particular form data at Server side inorder to perform Server side data validations, to
transfer data from Controller layer to model layer or Vie layer,.....
To prepare Form Bean components in Struts applications we have to use the following rules and
regulations.
EXAMPLE:
LoginActionForm.java
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Struts based web applications, the main intention of Action class is to manage application logic
which we want to execute by getting request from client.
In Struts based web applications, to prepare Action class we have to use the following steps.
Note:In execute() method we must return ActionForward object with a particular Forward key
inorder to identify target view page, for this, we have to use the following method from
ActionMapping.
EX: LoginAction.java
75
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
struts-config.xml
In Struts based web applications, the main intention of struts configuration file is to provide
mappings between user forms amd the respective ActionForm classes and Action classes
,...... which are required by the ActionServlet inorder to perform Server side actions.
In Struts based web applications, the default name and location of configuration file is
"struts-config.xml" and "WEB-INF" location, but, it is possible to change this default name
and location but we must give that new name and location to the Struts Framework.
In Struts based web applications, configuration file is able to provide the following
configurations.
1. Datasource configurations.
2. Global Forwards configurations.
3. Form Beans Configurations.
4. Action classes configurations.
5. Message Resources configurations.
6. Controller configurations.
7. Plugin configurations
8. Global Exceptions configurations.
To prepare basic Struts based web applications we need to provide ActionForm class
configuration and action class configuration in struts connfiguration file.
6. </form-beans>
7. <action-mappings>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where <struts-config> is a root tag, it will include struts application configuration details.
Where <form-beans> tag is able to include no of form beans configurations.
Where <form-bean> tag is able to provide single form bean class configuration.
Where "name" attribute in <form-bean> tag is able to provide logical name to Form Bean
component.
Where "type" attribute in <form-bean> tag will take fully qualified name of the respective
form bean class.
Where <action-mappings> tag is able to include no of actions configurations.
Where <action> tag is able to provide mapping between user form, ActionForm class and
the respective Action class.
Where "path" attribute in <action> tag is able to take url pattern which we specified in User
form.
Where "name" attribute in <action> tag will take logical name of the form bean class which
we specified in struts configuration file under form beans configurations.
Where "type" attribute in <action> tag is able to take fully qualified name of the Action
class.
Where <forward> tag is able to provide mapping between forward key which is returned
from execute() method in Action class and the target view page.
Where "name" attribute in <forward> tag is able to take forward key.
Where "path" attribute in <forward> tag is able to take the name and location of target view
page.
EX:
6. <action-mappings>
7. <action path="/login" name="loginForm" type="com.durgasoft.action.LoginAct
Page
ion">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Steps:
loginform.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>User Login Form</h3>
10. <form method="POST" action="login.do">
11. <table>
12. <tr>
13. <td>User Name</td>
14. <td><input type="text" name="uname"/></td>
15. </tr>
16. <tr>
17. <td>Password</td>
18. <td><input type="password" name="upwd"/></td>
78
19. </tr>
20. <tr>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
success.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>User Login Status</h3>
10. <font color="red" size="6">
11. <b>User Login Success</b>
12. </font>
13. <h5>
14. <a href="./loginform.html">|User Login Form|</a>
15. </h5>
16. </body>
17. </html>
Failure.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>User Login Status</h3>
10. <font color="red" size="6">
79
13. <h5>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
LoginActionForm.java
1. package com.durgasoft.beans;
2.
3. import org.apache.struts.action.ActionForm;
4.
5. public class LoginActionForm extends ActionForm {
6. private String uname;
7. private String upwd;
8.
9. public String getUname() {
10. return uname;
11. }
12. public void setUname(String uname) {
13. this.uname = uname;
14. }
15. public String getUpwd() {
16. return upwd;
17. }
18. public void setUpwd(String upwd) {
19. this.upwd = upwd;
20. }
21.
22. }
LoginAction.java
1. package com.durgasoft.action;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.apache.struts.action.Action;
80
7. import org.apache.struts.action.ActionForm;
8. import org.apache.struts.action.ActionForward;
Page
9. import org.apache.struts.action.ActionMapping;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
struts-config.xml
web.xml
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
82
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Hibernate:
1. Student.java
2. Student.hbm.xml
3. hibernate.cfg.xml
4. HibernateUtil.java
5. StudentService.java
Struts:
1. StudentRegistrationAction.java
2. StudentRegistrationActionForm.java
3. student_registration_form.html
4. success.html
5. failure.html
6. existed.html
7. struts-config.xml
8. web.xml
Example:
registrationform.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>Student Registration Form</h3>
10. <form method="POST" action="reg.do">
11. <table>
12. <tr>
13. <td>Student Id</td>
14. <td><input type="text" name="sid"/></td>
15. </tr>
16. <tr>
17. <td>Student Name</td>
83
20. <tr>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
success.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>Student Registration Status</h3>
10. <font color="red" size="6">
11. <b>
12. Student Registration Success
13. </b>
14. </font>
15. <h5>
16. <a href="./registrationform.html">|Student Registration Form|</a>
17. </h5>
18. </body>
19. </html>
failure.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
84
7. <body>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
existed.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8. <h2>Durga Software Solutions</h2>
9. <h3>Student Registration Status</h3>
10. <font color="red" size="6">
11. <b>
12. Student Existed Already
13. </b>
14. </font>
15. <h5>
16. <a href="./registrationform.html">|Student Registration Form|</a>
17. </h5>
18. </body>
19. </html>
StudentActionForm.java
1. package com.durgasoft.beans;
2.
3. import org.apache.struts.action.ActionForm;
85
4.
5. public class StudentActionForm extends ActionForm {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentAction.java
1. package com.durgasoft.action;
2.
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.apache.struts.action.Action;
7. import org.apache.struts.action.ActionForm;
8. import org.apache.struts.action.ActionForward;
9. import org.apache.struts.action.ActionMapping;
10.
11. import com.durgasoft.beans.StudentActionForm;
12. import com.durgasoft.service.StudentService;
13.
14. public class StudentAction extends Action {
86
15. @Override
16. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequ
Page
est request,
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentService.java
1. package com.durgasoft.service;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6.
7. import com.durgasoft.hbn.pojo.Student;
8. import com.durgasoft.hbn.util.HibernateUtil;
9.
10. public class StudentService {
11. String status = "";
12. public String registration(String sid, String sname, String saddr) {
13. try {
14. SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
15. Session session = sessionFactory.openSession();
16. Student std = (Student) session.get(Student.class, sid);
17. if(std == null) {
18. std = new Student();
19. std.setSid(sid);
20. std.setSname(sname);
21. std.setSaddr(saddr);
22. Transaction tx = session.beginTransaction();
23. session.save(std);
24. tx.commit();
25. status = "success";
26. }else {
87
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Student.java
1. package com.durgasoft.hbn.pojo;
2.
3. public class Student {
4. private String sid;
5. private String sname;
6. private String saddr;
7.
8. public String getSid() {
9. return sid;
10. }
11. public void setSid(String sid) {
12. this.sid = sid;
13. }
14. public String getSname() {
15. return sname;
16. }
17. public void setSname(String sname) {
18. this.sname = sname;
19. }
20. public String getSaddr() {
21. return saddr;
22. }
23. public void setSaddr(String saddr) {
24. this.saddr = saddr;
25. }
26.
27.
28. }
HibernateUtil.java
88
1. package com.durgasoft.hbn.util;
2.
Page
3. import org.hibernate.SessionFactory;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Student.hbm.xml
hibernate.cfg.xml
7. <property name="connection.driver_Class">com.mysql.jdbc.Driver</property>
8. <property name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
Page
9. <property name="connection.username">root</property>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
struts-config.xml
web.xml
7. <servlet>
8. <servlet-name>actionServlet</servlet-name>
Page
9. <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In the above application, Struts Framework will be loaded at the time of Server Startup, because,
ActionServlet initialization is performed at the time of Server Startup due to <load-on-startup>
configuration in ActionServlet configuration in web.xml file, but, Hibernate software is loaded after
the Server startup and after getting first request from client, it may take lot of time to load
Hibernate Software, it will increase response time and it will reduce application performance.
In the above context, to improve application performance we have to load Hibernate Software
along with Struts framework loading, that is, at the time of Server startup and as part of
ActionServlet initialization.
1) Prepare Our own Controller class by extending ActionServlet and override "init()"
method:
Example:
1. package com.durgasoft.controller;
2. import javax.servlet.ServletConfig;
3. import javax.servlet.ServletException;
4. import org.apache.struts.action.ActionServlet;
5. import com.durgasoft.hbn.util.HibernateUtil;
6. public class MyController extends ActionServlet {
7. public void init(ServletConfig config) throws ServletException {
8. super.init(config);
9. HibernateUtil.getSessionFactory();
10. System.out.println("****MyController-init()**********");
11. System.out.println("Struts Framework is Loaded");
12. System.out.println("Hibernate is Loaded");
91
13. System.out.println("*********MyController-init()********");
14. }
Page
15. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <web-app>
2. <welcome-file-list>
3. <welcome-file>registrationform.html</welcome-file>
4. </welcome-file-list>
5. <servlet>
6. <servlet-name>myController</servlet-name>
7. <servlet-class>com.durgasoft.controller.MyController</servlet-class>
8. <load-on-startup>1</load-on-startup>
9. </servlet>
10. <servlet-mapping>
11. <servlet-name>myController</servlet-name>
12. <url-pattern>*.do</url-pattern>
13. </servlet-mapping>
14. </web-app>
To prepare Hibernate PlugIn class, declare an user defined class and implement
org.apache.struts.action.PlugIn interface and provide implementat6ion for the following methods.
Ex:
1. package com.durgasoft.plugin;
2. import javax.servlet.ServletException;
92
3. import org.apache.struts.action.ActionServlet;
4. import org.apache.struts.action.PlugIn;
Page
5. import org.apache.struts.config.ModuleConfig;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <struts-config>
2. ----
3. <plug-in className="com.durgasoft.plugin.HibernatePlugIn"/>
4. ----
5. </struts-config>
Internal Flow:
1. Container will deploye all web applications which are available in webapps folder or in
deployments folder.
2. Container will recognize web.xml file and perform web.xml file loading and parsing.
3. Container will recognize <load-on-startup> configuration in ActionServlet configuration in
web.xml file then performs ActionServlet loading, instantiation and initialization.
4. As part of ActionServlet initialization, ActionServlet will recognize struts configuration file
then performs struts configuration file loading and parsing.
5. ActionServlet will recognize <plug-in> tag in struts configuration file and identify
HibernatePlugIn class .
6. ActionServlet will perform HibernatePlugIn class loading , instantiation and initialization.
7. As part of HibernatePlugIn class initialization,ActionServlet will load Hibernate software and
prepare Configuration and SessionFactory objects with HibernateUtil class at the time of
Server startup.
93
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Ans:
Yes, in single hibernate application we are able to interact with more than one Database, but, we
must use the following conventions.
1) We must provide separate configuration file for each and every Database.
2) Use either single mapping file if we have same table name and same columns in both the
databases tables and use different mapping file for each and every database if we have
difference in table names and column names.
3) In Client application.
a) Prepare Seperate Configuration object for each and every DB.
b) Prepare seperate SessionFactory object for each and every DB.
c) Prepare seperate Session object for each and every DB.
d) Prepare Seperate Transaction object for each and every DB as per the requirement.
e) Perform persistance operations on DB respective Session objects.
Example:
Employee.java
1. package com.durgasoft.hbn.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8. public int getEno() {
9. return eno;
10. }
11. public void setEno(int eno) {
12. this.eno = eno;
13. }
14. public String getEname() {
15. return ename;
16. }
17. public void setEname(String ename) {
18. this.ename = ename;
94
19. }
20. public float getEsal() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
hibernate_oracle.cfg.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate_mysql.cfg.xml
ClientApp.java
1. package com.durgasoft.hbn.client;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.cfg.Configuration;
7.
8. import com.durgasoft.hbn.pojo.Employee;
9.
10. public class ClientApp {
11.
12. public static void main(String[] args) {
13. SessionFactory oracle_SessionFactory = null;
96
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ANS:
Yes, it is possible to run hibernate applications with out using mapping file, but, we have to use
97
Annotations.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. @Entity:
2. @Table(name="--")
This annotation is a class level annotation, it can be used to configure table name for the entity
class. Where "name" member is able to provide the respective table name.
3. @Id :
4. @Column(name="--")
Ex: Employee.java
1. @Entity
2. @Table(name="emp1")
3. public class Employee{
4. @Id
5. @Column(name="ENO")
6. private int eno;
98
7. @Column(name="ENAME")
8. private String ename;
Page
9. @Column(name="ESAL")
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
1. <hibernate-configuration>
2. ---
3. <mapping class="com.durgasoft.hbn.pojo.Employee"/>
4. ----
5. </hibernate-Configuration>
ClientApp.java:
Same as previous applications.
Example:
Employee.java
1. package com.durgasoft.hbn.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="emp1")
10. public class Employee {
11. @Id
12. @Column(name="ENO")
13. private int eno;
14. @Column(name="ENAME")
15. private String ename;
16. @Column(name="ESAL")
17. private float esal;
99
18. @Column(name="EADDR")
19. private String eaddr;
Page
20.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
5. <hibernate-configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.cfg.AnnotationConfiguration;
6. import org.hibernate.cfg.Configuration;
7.
8. import com.durgasoft.hbn.pojo.Employee;
9.
10. public class ClientApp {
11.
12. public static void main(String[] args) {
13. SessionFactory sessionFactory = null;
14. Session session = null;
15. try {
16. //Configuration cfg = new AnnotationConfiguration();
17. Configuration cfg = new Configuration();
18. cfg.configure();
19. sessionFactory = cfg.buildSessionFactory();
20. session = sessionFactory.openSession();
21. Employee emp = (Employee)session.get(Employee.class, 111);
22. if(emp == null) {
23. System.out.println("Employee Not Existed");
24. }else {
101
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ANS:
In Hibernate Applications, we are able to provide configuration details in the following two
approaches.
1) Programmatic Approach
2) Declarative Approach
a) By using properties file
b) By Using XML file
1) Programmatic Approach
To add mapping file name and location to Configuration file we have to use the following method.
102
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example on without configuration File and with mapping file in Programmatic Approach:
Employee.java
1. package com.durgasoft.hbn.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. this.esal = esal;
26. }
27. public String getEaddr() {
28. return eaddr;
29. }
30. public void setEaddr(String eaddr) {
103
34. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.cfg.AnnotationConfiguration;
6. import org.hibernate.cfg.Configuration;
7.
8. import com.durgasoft.hbn.pojo.Employee;
9.
10. public class ClientApp {
11.
12. public static void main(String[] args) {
13. SessionFactory sessionFactory = null;
14. Session session = null;
15. try {
16. // Configuration cfg = new AnnotationConfiguration();
17. Configuration cfg = new Configuration();
18. cfg.setProperty("hibernate.connection.driver_Class","oracle.jdbc.OracleDriver");
19. cfg.setProperty("hibernate.connection.url","jdbc:oracle:thin:@localhost:1521:xe");
104
23. cfg.addResource("Employee.hbm.xml");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example on without configuration file and without mapping file in Programmatic approach:
Employee.java
1. package com.durgasoft.hbn.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="emp1")
105
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
106
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
Page
4. import org.hibernate.SessionFactory;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
44. }
45.
46. }
Page
47. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2) Declarative approach:
In Declarative approach, we will provide all configuration details in either properties file or in XML
file then we will send configuration details to Hibernate application.
There are two ways to provide configuration details to Hibernate Applications in Declarative
Approach.
1) By using properties file.
2) By Using XML file.
In This approach, to provide all hibernate configuration details , we have to declare a properties
file with the default name "hibernate.properties" under "src" folder . In this context, when we create
Configuration class object , Hibernate Software will search for the properties file with the name
"hibernate.properties" and get all the configuration details into Configuration class object.
In this approach we must add mapping file explicitly to Configuration File by using the following
method.
Example:
hibernate.properties:
hibernate.connection.driver_Class = oracle.jdbc.OracleDriver
hibernate.connection.url = jdbc:oracle:thin:@localhost:1521:xe
hibernate.connection.username = system
hibernate.connection.password = durga
hibernate.dialect = org.hibernate.dialect.OracleDialect
ClientApp.java
108
1. class ClientApp{
2. public static void main(String[] args){
3. Configuration cfg = new Configuration();
Page
4. cfg.addResource("Employee.hbm.xml");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: If we change name and location of properties file from hibernate.properties to some other
abc.properties then we have to give that intemation to Hibernate software, for this, we have to
create FileInputStream and Properties class object then we have to set Properties object to
Configuration class object by using the following method.
Example:
abc.properties:
hibernate.connection.driver_Class = oracle.jdbc.OracleDriver
hibernate.connection.url = jdbc:oracle:thin:@localhost:1521:xe
hibernate.connection.username = system
hibernate.connection.password = durga
hibernate.dialect = org.hibernate.dialect.OracleDialect
Employee.hbm.xml
Employee.java
109
1. package com.durgasoft.hbn.pojo;
2. public class Employee {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3. import java.io.FileInputStream;
4. import java.util.Properties;
5.
110
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8. import org.hibernate.cfg.AnnotationConfiguration;
Page
9. import org.hibernate.cfg.Configuration;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
48. }
49.
50. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use xml file to provide all configuration details then we have to use configure()
method to get all configuration details from xml file. Here configure() method will search for
xml file with the default name hibernate.cfg.xml under src folder inorder to get configuration
details. If we change the default name and location of hibernate configuration file then we
have to pass that name and location to configure(--) method as parameter.
Composite Keys:
In Database applications, if one column is not sufficient to manage uniqueness as primary key
then it is possible to declare more than one column combnation as primary key, such type of
column combination as primary key is called as "Composite Key".
sql>create table emp1(ENO number, ENAME varchar2(10), ESAL float, EADDR varchar2(10),
primary key(ENO,ENAME));
sql>commit
To rerpesent Composite keys in Hibernate applications we have to use the following xml tags in
mapping file.
1. <hibernate-mapping>
2. <class name="--" table="--">
3. <composite-id>
4. <key-property name="--" column="--"/>
5. -----
6. </compisite-id>
7. ----
8. </class>
9. </hibernate-mapping>
112
composite key.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where "name" attribute will take id property name and column attribute will take "database
table column name".
EX:Employee.hbm.xml
1. <hibernate-mapping>
2. <class name="com.durgasoft.hbn.pojo.Employee" table="emp1">
3. <composite-id>
4. <key-property name="eno" column="ENO"/>
5. <key-property name="ename" column="ENAME"/>
6. </composite-id>
7. <property name="esal" column="ESAL"/>
8. <property name="eaddr" column="EADDR"/>
9. </class>
10. </hibernate-mapping>
11.
12. Note: To declare compisite keys in annotated classes , no need to use any seperate Annot
ation, simply we have to declare @Id annotation at both the columns.
13.
14. EX: Employee.java
15. -----------------
16. @Entity
17. @Table(name="emp1")
18. public class Employee implements Serializable {
19. @Id
20. @Column(name="ENO")
21. private int eno;
22. @Id
23. @Column(name="ENAME")
24. private String ename;
25. @Column(name="ESAL")
26. private float esal;
27. @Column(name="EADDR")
28. private String eaddr;
29. setXXX() and getXXX()
30. }
113
Note: To use Composite keys feature in Hibernate applications then it is mandatory to implement
java.io.Serializable marker interface to POJO class.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.hbn.pojo;
2.
3. import java.io.Serializable;
4.
5. import javax.persistence.Column;
6. import javax.persistence.Entity;
7. import javax.persistence.Id;
8. import javax.persistence.Table;
9. @Entity
10. @Table(name="emp1")
11. public class Employee implements Serializable {
12. @Id
13. @Column(name="ENO")
14. private int eno;
15. @Id
16. @Column(name="ENAME")
17. private String ename;
18. @Column(name="ESAL")
19. private float esal;
20. @Column(name="EADDR")
21. private String eaddr;
22.
23. public int getEno() {
24. return eno;
25. }
26. public void setEno(int eno) {
27. this.eno = eno;
28. }
29. public String getEname() {
30. return ename;
31. }
32. public void setEname(String ename) {
33. this.ename = ename;
34. }
114
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
hibernate.cfg.xml
8. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
9. <property name="connection.user">system</property>
10. <property name="connection.password">durga</property>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3.
4. import org.hibernate.Session;
5. import org.hibernate.SessionFactory;
6. import org.hibernate.Transaction;
7. import org.hibernate.cfg.Configuration;
8.
9. import com.durgasoft.hbn.pojo.Employee;
10.
11. public class ClientApp {
12.
13. public static void main(String[] args) {
14. SessionFactory sessionFactory = null;
15. Session session = null;
16. try {
17.
18. Configuration cfg = new Configuration();
19. cfg.configure();
20. sessionFactory = cfg.buildSessionFactory();
21. session = sessionFactory.openSession();
22.
23. Employee emp1 = new Employee();
24. emp1.setEno(222);
25. emp1.setEname("BBB");
26. emp1.setEsal(8000);
27. emp1.setEaddr("Hyd");
28. Transaction tx = session.beginTransaction();
29. session.save(emp1);
30. tx.commit();
31. System.out.println("Employee Inserted Successfully");
116
32.
33. /*
34. Employee emp_Key = new Employee();
Page
35. emp_Key.setEno(222);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
117
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The collective information of any object right from starting point to end point is called as Object
Lifecycle.
1. Transient State
2. Persistence State
3. Ditached State
4. Removed State
1. Transient State
In Hibernate Applications, when we create POJO object then automatically POJO object
118
If POJO object is available in Transient State then Hibernate Software is not aware about
Page
POJO object.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If POJO object is available in Transient State then POJO object is representing any record
in Database table.
In this state, Hibernate Software is unable to provide synchronization between POJO object
and record in Database.
In this state, if we perform modifications in POJO object then that modifications are not
reflected to any record in Database.
If we keep POJO object in Transient State for long time then POJO object is eligible for
Garbage Collection then Garbage Collector will destroy POJO object.
2. Persistence State:
If we perform the Operations like save() , update(), saveOrUpdate(),.... over the POJO
object which is available in Transient State then POJO object will come to Persistence
State.
In Hibernate Applications, if we perform the objects like get() , load(), find(),... automatically
Hibernate Software will create POJO object in Persistence State directly without Transient
State.
In Persistence State, Hibernate Software is aware about POJO Object and database table
record and its synchronization.
3. Ditached State:
If we perform the operations like close(), clear(), evict(),.... over the Session object then
POJO object will come from Persistence State to Ditached State.
In Ditached State, Hibernate Software is not aware about POJO object and it will not
provide synchroinization between POJO object and database table record.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we keep POJO object in Ditached State for long time then POJO object is eligible for
Garbage Collection, where Garbage Collector will destroy that object.
4. Removed State:
If we perform the operations like remove() or delete() over the POJO object in Persistence
state then POJO object will come from Persistence State to Removed State.
In Removed State, POJO object is not representing any record in Database table.
In Hibernate Applications, Once if POJO object is in Removed State then it is not possible
to get back into Persistence State, directly, it must go for Garbage Collection only.
Example:
Employee emp = new Employee();// Transient State
----
session.save(emp);// Persistence State
----
----
session.delete(emp); Removed State
Example:
Account acc = new Account(); // Transient State
---
---
session.save(acc); // Persistence State
---
----
session.close(); // Ditached State
----
----
120
sessionFactory.getCurrentSession(); or sf.openSession();
----
session.update(acc); // Persistence
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate applications, to perform DML operations like insert, update, delete ,... we will use the
methods lile save(), update(), delete(),... from org.hibernate.Session interface provided by
Hibernate Software.
In Hibernate applications, to perform DDL operations like create, alter, drop,... Hibernate has
provided the following implicit tools.
1. SchemaExport
2. SchemaUpdate
3. CodeGeneration
Note: The above Shema generation tools are usefull to create tables when we want to work with
unknown databases.
1. SchemaExport
a) First SchemaExport tool will take name and location of hibernate configuration file which we
have provided as input parameter.
b) SchemaExport tool will load and parse hibernate configuration file.
c) SchemaExport tool will recognize mapping file configuration in hibernate configuration file
then it will load and parse mapping file.
d) As per mapping file details, SchemaExport tool will check whether any table is existed or
not in Database.
e) If no table is existed then SchemaExport tool will create new table as per mapping file
details.
f) If any table is existed with the name then SChemaExport tool will drop that existed table
and creates new table as per mapping file configuration details.
To activate SchemaExport tool manually through command prompt then we have to use the
following command on command prompt.
121
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Customer.java
32. }
33. public String getCaddr()
Page
34. {
35. return caddr;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Customer.hbm.xml
hibernate.cfg.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
a) First SchemaUpdate tool will take name and location of hibernate configuration file which
we have provided as input parameter.
b) SchemaUpdate tool will load and parse hibernate configuration file.
c) SchemaUpdate tool will recognize mapping file configuration in hibernate configuration file
then it will load and parse mapping file.
d) As per mapping file details, SchemaUpdate tool will check whether any table is existed or
not in Database with the same name.
e) If no table is existed then SchemaUpdate tool will create new table as per mapping file
details.
f) If any table is existed with the name then SChemaUpdate tool will alter that existed table as
per mapping file configuration details.
Note: When mapping contains new colums details when compared with database table then only
SchemaUpdate tool will perform alter operation. If Database table contains more columns when
compared with mapping file configuration details then SchemaUpdate tool will not perform alter
operation.
To activate SchemaUpdate tool manually through command prompt then we have to use the
following command on command prompt.
Note: To run the above command we must copy all hibernate jars to "C:\Java\jdk1.7.0\jre\lib\ext"
folder and we must provide POJO class, mapping file and configuration file at the same location
from where we are activating SchemaUpdate tool.
Customer.java
7.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Customer.hbm.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
3. CodeGeneration:
The mian intention of CodeGeneration tool is to create POJO class as per database table
configurations which we provided in mapping file.
Note: This is available upto Hibernate2.x version, but, it is deprecated in Hibernate3.x version.
1. create
2. update
Page
3. create-drop
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
1. <hibernate-configuration>
2. ----
3. <property name="hibernate.hbm2ddl.auto">create</property>
4. ----
5. </hibernate-configuration>
2. Update: This option for "hibernate.hbm2ddl.auto" property will activate SchemaUpdate tool, it
will create table if table is not existed, it will alter the table if table is existed as per the mapping
file.
EX:
1. <hibernate-configuration>
2. ----
3. <property name="hibernate.hbm2ddl.auto">update</property>
4. ----
5. </hibernate-configuration>
3. Create-Drop: This option for "hibernate.hbm2ddl.auto" will create table when SessionFactory
object is created and it will drop table when SessionFactory object is closed.
EX:
1. <hibernate-configuration>
2. ----
3. <property name="hibernate.hbm2ddl.auto>create-drop</property>
4. ----
5. </hibernate-configuration>
127
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate4.x version, to create SessionFactory object we have to use the following steps.
c) Creating StandardServiceRegistryBuilder:
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
stry registry)
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.hbn.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. this.esal = esal;
26. }
27. public String getEaddr() {
28. return eaddr;
29. }
30. public void setEaddr(String eaddr) {
31. this.eaddr = eaddr;
32. }
33.
34.
35. }
129
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
130
5. import org.hibernate.boot.registry.StandardServiceRegistry;
6. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
7. import org.hibernate.cfg.Configuration;
Page
8.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
131
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Primary key is single column or Collection of columns in a table to recognize the records
individually.
In Database applications, we are unable to give option to the users to enter primary key
values , because, there is no guarantee for the data entered by the users whether it is
unique data or not, but, in Database tables only unique values are accepted by primary key
columns.
To give guarantee for uniqueness in primary key values we have to use Primary key
generation algorithms.
Almost all the Persistence mechanisms like Hibernate, JPA, Open JPA, Toplink,.... are
having their own implementation for primary key generation algorithms.
Hibernate has provided support for the following primary key generation algorithms inorder to
generate primary key values.
1. assigned
2. increment
3. sequence
4. identity
5. hilo
6. native.
7. seq-hilo
8. select
9. UUID
10. GUID
11. foreign
Hibernate has represented all the above primary key generation algorithms in the form of a set of
predefined classes provided in
"org.hiberante.id" package.
132
If we want to use any of the above algorithms in Hibernate applications then we have to configure
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where <generator> tag will represent a particular primary key generation algorithm.
Where "class" attribute in <generator> tag will take either short name or Fully qualified
name of Generator class.
Where <param> tag will provide single input parameter to the Primary key generator
inorder to generate primary key value.
Where "name" attribute in <param> tag will take parameter name , here we have to provide
parameter value as body to the <param> tag.
1. assigned
This algorithm is default primary key generation algorithm in hibernate applications, it will
not required configurations in mapping file.
This algorithm will not have its own mechanism to generate primary key value , it will
request to Client Application to provide primary key value explicitly.
This algorithm is able to support for any type of primary key values like short, int, long,
String,.....
This alg is supported by almost all the databases like Oracle, MySQL, DB2, ......
This alg is not required any input parameter.
This alg is represented by Hibernate in the form of a predefined class
"org.hibernate.id.Assigned".
EX:
3. <generator class="assigned"/>
4. </id>
5. ----
Page
6. </class>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This primary key generation algorithm is able to generate primary key value by
incrementing max value of the primary key column.
New_Val = max(PK_Column)+1
This alg is able to generate primary key values of the data types like short, int, long,...
This alg is not required any input parameter to generate primary key values.
This alg is supported by almost all the databases which are supporting numeric values as
Primary key values.
This alg is representned by Hibernate Software in the form of a short name "increment" and
in the form of a predefined class like "org.hibernate.id.IncrementGenerator".
EX:
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO">
4. <generator class="org.hibernate.id.IncrementGenerator"/>
5. </id>
6. ----
7. </class>
8. </hibernate-mapping>
3. sequence
This primary key generation algorithm is able to generate primary key value on the basis of
the sequence provided by the underlying Database.
This alg is able to generate primary key values of the data types like short, int, long,...
This alg required "sequence" input parameter with the sequence name as value inorder to
generate primary key value.
If we have not provided any sequence name as input parameter then this alg is able to take
"hibernate_sequence" as default sequence name, here developers must create
"hibernate_sequence" in database explicitly.
This alg is supported by almost all the databases which are supporting sequences like
Oracle, DB2,....
This alg is represented by Hibernate Software in the form of a short name like "sequence"
and in the form of a predefined class like "org.hibernate.id.SequenceGenerator".
EX:
134
In Database:
SQL>create sequence my_sequence increment by 5;
Page
SQL>commit;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO">
4. <generator class="sequence">
5. <param name="sequence">my_sequence</param>
6. </generator>
7. </id>
8. -----
9. </class>
10. </hibernate-mapping>
Note: If we dont want to use explicit sequence then we must create default sequence in database
, that is, "hibernate_sequence".
4. identity
This alg is able to generate primary key values on the basis on the underlying database
table provided identity column.
Note: Identity column is a primary key Column with "auto_increment" capability.
This alg is able to provide the primary key values of the data types like short, int, long,....
This alg is not required any input parameter.
This alg is supported by almost all the databases which are supporting Identity column.
EX: MySQL.
To represent this alg, Hibernate has provided "identity" as short name and
"org.hibernate.id.IdentityGenerator" as predefined class.
EX:
IN MySQL database:
sql>create table emp1(ENO primary key auto_increment, ENAME char(10), ESAL float, EADDR
char(10));
IN Mapping File:
1. <hibernate-mapping>
135
4. <generator class="identity"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
5. hilo[High-Low]
This alg is able to generate primary key value by getting high value from a particular global
resource and low value from mapping file.
Note: Global resource is a particular table with a column in the same database.
This alg is able to generate primary key values of the data types like short, int, long,....
To represent this alg. Hibernate software has provides a seperate short in the form of "hilo"
and a seperate predefined class in the form of "org.hibernate.id.TableHiLoGenerator".
This alg is supported by almost all the databases like Oracle, MySQL,....
To generate primary key value this alg will take the following three parameters.
1. table: Global resource name , that is, a table name which provides high value.
2. column:column name existed in Global Resource to manage high value.
3. max_lo:It will provide low value .
Note: If we have not provided Global resources parameters like table and column in mapping file
then Hibernate Software will take high value from default global resource table
"hibernate_unique_key" and column "next_hi".
EX:
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO">
4. <generator class="hilo">
5. <param name="table>my_table</param>
6. <param name="column">my_column</param>
7. <param name="max_lo">10</param>
8. </generator>
9. </id>
10. ----
11. </class>
12. </hibernate-mapping>
136
13. In Database:
14. SQL>create table my_table(my_column number primary key);
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: If we want to use default table name and column instead of my_table and my_column then
we have to remove "table" and "column" parameters in mapping file and provide the following in
Database.
6. native
This alg is able to generate primary key value by selecting a particular primary key
generation alg depending on the database which we used.
This alg is not having its own alg to generate primary key value. It will select
"SequenceGenerator" alg if we are using Oracle database, "IdentityGenerator" alg if we are
using MySQL database and "TableHiLoGenerator" if we are using some other database
which is not supporting SequenceGenerator and IdentityGenerator.
This Primary key generator is able to generate primary key values of the data types like
short, int, long,...
This primary key generator is supported by almost all the databases.
To represent this mechanism, Hibernate has provided a short name in the form of "native",
Hibernate has not provided any predefined class.
This alg is able to take parameters on the basis of the selected primary key generator
depending on the database. If it is using "SequenceGenerator" then we must provide
"sequence" parameter. If it is using TableHiloGenerator then we have to provide "table",
"column", "max_lo" parameters.
EX:
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO">
4. <generator class="native">
5. ---provide parameters depending on requirement---
6. </generator>
7. </id>
8. </class>
9. </hibernate-mapping>
137
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This alg is able to generate primary key values on the basis of the sequence value provided
by the underlying database and the mapping file provided max_lo property valye.
This alg is almost all same as HiLo alg but in "seqhilo" alg we will get sequence vaue
inplace of the high value from Global resouce.
This alg is able to generate primary key values of the data types like short, int and long.
This alg is represented by Hibernate software in the form a short name like "seqhilo" and a
predefined class name like "org.hibernate.id.SequenceHiLoGenerator".
This alg is supported by almost all the databases which are supporting sequences
internally.
This alg is required the following two input parameters.
EX:
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO">
4. <generator class="seqhilo">
5. <param name="sequence">my_sequence</param>
6. <param name="max_lo">10</param>
7. </generator>
8. </id>
9. ----
10. </class>
11. </hibernate-mapping>
8. select
This alg is able to generate promary key values on the basis of the underlying database
provided triggers.
This alg is able to provide primary key values of the data types like short, int and long.
This alg is represented by Hibernate software in the form of a short name like "select" and
138
This alg is supported by almost all the databases which are supporting triggers.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO">
4. <generator class="select">
5. --- parameters related to triggers----
6. </generator>
7. </id>
8. -----
9. </class>
10. </hibernate-mapping>
This alg is able to generate primary key value on the basis of System IP-Address , JVM
Startup time, Current System time,.... factors.
This alg is able to generate primary key value in the form of 32 bit hexa decimal value.
This alg is able to generate primary key value of the data type like String.
This alg is represented by Hibernate software in the form of a short name "uuid" and a
predefined class name "org.hibernate.id.UUIDHexGenerator".
This alg is supported by almost all the databases which are supporting String type primary
key values.
This alg is not required any input parameters, but, it must required "varchar" type primary
key column with 32 column size minimum in database table.
EX:
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO" type="string">
4. <generator class="org.hibernate.id.UUIDHexGenerator"/>
5. </id>
6. ----
7. </class>
8. </hibernate-mapping>
10. GUID
This alg is able to generate primary key values on the basis of the underlying database
139
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO">
4. <generator class="org.hibernate.id.GUIDGenerator"/>
5. </id>
6. ----
7. </class>
8. </hibernate-mapping>
11. foreign
This primary key generation alg is able to generate primary key values on the basis of the
foreign key of the present table.
This alg is able to generate primary key values of the data types like short, int and long.
This alg is not required any input parameters to generate primary key values.
This alg is represented by Hibernate software in the form of a short name "foreign" and in
the form of a predefined class like "org.hibernate.id.ForeignGenerator".
EX:
1. <hibernate-mapping>
2. <class name="Employee" table="emp1">
3. <id name="eno" column="ENO">
4. <generator class="org.hibernate.id.ForeignGenerator"/>
5. </id>
6. ----
7. </class>
8. </hibernate-mapping>
To provide annotations for primary key generation alg javax.persistence package has provided the
following annotations.
140
@GeneratedValue(--,--)
@SequenceGenerator(--)
Page
@TableGenerator(--)
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To provide a particular primary key generation alg in hibernate applications, we have to use
"strategy" member in @GeneratedValue(-) annotation, it will take either of the following constants
from "GenerationType" Enum.
1. IDENTITY
2. SEQUENCE
3. TABLE
4. AUTO
EX: Employee.java
1. @Entity
2. @Table(name="emp1")
3. public class Employee {
4. @Id
5. @Column(name="ENO")
6. @GeneratedValue(strategy=GenerationType.IDENTITY)
7. private int eno;
8. @Column(name="ENAME")
9. private String ename;
10. @Column(name="ESAL")
11. private float esal;
12. @Column(name="EADDR")
13. private String eaddr;
14. setXXX() and getXXX()
15. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: Employee.java
1. @Entity
2. @Table(name="emp1")
3. public class Employee {
4. @Id
5. @Column(name="ENO")
6. @SequenceGenerator(name="seqGen", sequenceName="my_sequence")
7. @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seqGen")
8. private int eno;
9. @Column(name="ENAME")
10. private String ename;
11. @Column(name="ESAL")
12. private float esal;
13. @Column(name="EADDR")
14. private String eaddr;
15. setXXX() and getXXX()
16. }
3. TABLE: This constant from GenerationType enum is able to represent HiLo Primary key
generation alg inorder to generate primary key values on the basis of Global resource. To
configure Global resource table and its properties we have to use @TableGenerator() annotation
with the following members.
1. name: it will take logical name to the @TableGenerator
2. pkColumnName: it will take primary key column name of the Global resource table.
3. pkColumnValue: It will take initial value to the primary key column in global resource
table.
4. valueColumnName: it will take a column name which is generating our required
primary key value.
5. table: it will take Global resource table name.
EX: Employee.java
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. AUTO: This constant from GenerationType enum is able to represent "native" primary key
generation alg inorder to generate primary key value by selecting either sequence or identity or
hilo primary key generation algorithms on the basis of the under lying database.
Note: Depending on the database or depending on the internal primary key generation alg we
have to provide4 input parameters by using @SequenceGenerator() or @TableGenerator()
annotations.
EX: Employee.java
1. @Entity
2. @Table(name="emp1")
3. public class Employee {
4. @Id
5. @Column(name="ENO")
6. @SequenceGenerator(name="seqGen", sequenceName="my_sequence")
7. @GeneratedValue(strategy=GenerationType.AUTO, generator="seqGen")
8. private int eno;
143
9. @Column(name="ENAME")
10. private String ename;
11. @Column(name="ESAL")
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: For the remaining primary key generation alg , Hibernate has provided the following
annotation in org.hibernate.annotation package.
@GenericGenerator(name="--", strategy="--",parameters={...})
@GeneratedValue(generator="--")
1. @Entity
2. @Table(name="emp1")
3. public class Employee{
4. @Id
5. @Column(name="ENO")
6. @GenericGenerator(name="incGen" strategy="increment")
7. @GeneratedValue(generator="incGen")
8. private int eno;
9. ----
10. ----
11. }
EXAMPLE:
Employee.java
1. package com.durgasoft.hbn.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
144
5. import javax.persistence.GeneratedValue;
6. import javax.persistence.GenerationType;
7. import javax.persistence.Id;
Page
8. import javax.persistence.SequenceGenerator;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
47. }
48. public String getEname() {
49. return ename;
Page
50. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. package com.durgasoft.hbn.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.hbn.pojo.Employee;
11.
12. public class Test {
13.
14. public static void main(String[] args)throws Exception {
15. Configuration cfg = new Configuration();
16. cfg.configure();
17. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
18. builder = builder.applySettings(cfg.getProperties());
19. StandardServiceRegistry registry = builder.build();
20. SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
21. Session session = sessionFactory.openSession();
22. Employee emp = new Employee();
23. //emp.setEno(111);
24. emp.setEname("AAA");
25. emp.setEsal(5000);
26. emp.setEaddr("Hyd");
27. Transaction tx = session.beginTransaction();
28. session.save(emp);
29. tx.commit();
147
33. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Atomicity: This property will make the Transaction either in SUCCESS state or in
FAILURE state.
In Database related applications, if we perform all operations then the Transaction is
available in SUCCESS State, if we perform none of the operations then the Transaction is
available in FAILURE state.
2. Consistency: In database applications, Before the Transaction and After the Transaction
Database state must be in stable.
3. Isolation: If we run more than one Transaction on a single Data item then that
Transactions are called as "Concurret Transactions". In Transactions Concurrency , one
transaction execution must not give effect to another Transaction, this rule is called as
"Isolation" property.
4. Durability: After committing the Transaction, if any failures are coming like Power failure,
OS failure,...after getting the System if we open the transaction then the modifications
which we performed during the transaction must be preserved.
148
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
Transaction tx = null;
try{
-----
tx = session.beginTransaction();
----
-----
tx.commit();
}catch(Exception e){
tx.rollback();
}
Example:
Employee.java
149
1. package com.durgasoft.pojo;
Page
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
oracle_cfg.xml
8. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
9. <property name="connection.username">system</property>
10. <property name="connection.password">durga</property>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
mysql_cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.Account;
11.
12. public class Test {
13.
151
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
58. oracle_Tx.commit();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we execute more than one transaction on a single data item then that transactions are called as
Concurrent Transactions.
In Transactions concurrency we are able to get the following data consistency problems while
executing more than one transaction at a time.
In Transactions concurrency, if one transaction perform updations over the data with out commit
operation , mean while, other transactions perform updations with commit operation then the first
transaction updations are lost, this data consistency problem is called as Lost Update problem.
153
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
154
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
155
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: con.setTransactionIsolation(Connection.TRANSACTION_READ_
COMMITTED);
<property name="hibernate.connection.isolation>val</property>
NONE = 0;
READ_UNCOMMITTED = 1;
READ_COMMITTED = 2;
REPEATABLE_READ = 4;
SERIALIZABLE = 8;
EX:
1. <hibernate-configuration>
2. <session-factory>
3. ----
4. <property name="hibernate.connection.isolation>
5. SERIALIZABLE
6. </property>
7. -----
8. </session-factory>
9. </hibernate-configuration>
156
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Connection Pooling, first, we will create a pool object with a set of Connection objects at
application loading time , then, we get Connection object from Pool when we want to
perform database operations, after the database operations we will send Connection object
back to Pool object with out destroying Connection object.
To provide Connection pooling in JDBC applications we have to use the following steps.
DataSource is an object , it able to manage all JDBC parameters inorder to create Connection
objects and it able to manage Pool objects with Connection objects.
In JDBC, to represent DataSource object, JDBC has provided a predefined interface in the form of
javax.sql.DataSource and its implementationa are provided by database vendors.
In DataSource, to create Connection objects in POOL , we have to provide Driver URL, Database
User Name and Database password,....., for this, we have to use the following methods.
157
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ds.setURL("jdbc:oracle:thin:@localhost:1521:xe");
ds.setUser("system");
ds.setPassword("durga");
To get Connection object from DataSource we have to use the following method.
public Connection getConnection()
EX: con.close();
Note: When we access close() on Connection object which we get from Pool , then, Connection
object will not be destroyed, whene Connection object will be send back to Pool object.
EX:
1. package com.durgasoft.jdbc;
2.
3. import java.sql.Connection;
4. import java.sql.ResultSet;
5. import java.sql.Statement;
6.
7. import oracle.jdbc.pool.OracleDataSource;
8.
9. public class ConnectionPoolingEx {
10. public static void main(String[] args) throws Exception {
11. OracleDataSource ds = new OracleDataSource();
12. ds.setURL("jdbc:oracle:thin:@localhost:1521:xe");
13. ds.setUser("system");
158
14. ds.setPassword("durga");
15. Connection con = ds.getConnection();
16. Statement st = con.createStatement();
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Hibernate Software has implemented its built-in connection pooling mechanism in the form of a
predefined class like
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
Hibernate provided built-in Connection pooling mechanism is able to allow 20 Connections as max
count and 1 connection as min count, we can modify this pool size in hibernate applications as per
the requirement by using "connection.pool_size" property in hibernate configuration file.
1. <hibernate-configuration>
2. <session-factory>
3. -----
4. <property name="connection.pool_size">10</property>
5. -----
6. </session-factory>
7. </hibernate-configuration>
Note: Hibernate Software provided built-in connection pooling mechanism is suggestible upto
159
Development and Testing phases, it is not suggestible for Production mode of our project.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. DBCP
2. C3P0
3. Proxool
Note: Hibernate is not providing support for DBCP Connection pooling mechanism, but, Hibernate
has provided predefined support for C3P0 and Proxool connection pooling mechanisms.
If we want to use C3P0 Connection pooling mechanism in hibernate applications then we have to
declare the following properties in hibernate configuration file.
1. hibernate.connection.provider_class:
This property will take Connection Pooling provider class which was provided by hibernate
software for C3P0 connection pooling mechanism in the form of
"org.hibernate.c3p0.internal.C3P0ConnectionProvider".
2. hibernate.c3p0.min_size:
It will take an int value which is representing minimum no of Connection objects in a pool.
3. hibernate.c3p0.max_size:
It will take int value which is representing maximum no of Connection objects in a pool.
4. hibernate.c3p0.timeout:
5. hibernate.c3p0.max_statements:
160
It will take an int value representing no of statements max for Connection objects.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX: hibernate.cfg.xml
1. <hibernate-configuration>
2. <session-factory>
3. -----
4. <property name="connection.pool_size">10</property>
5. -----
6. </session-factory>
7. </hibernate-configuration>
8. <hibernate-configuration>
9. <session-factory>
10. <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
12. <property name="connection.username">system</property>
13. <property name="connection.password">durga</property>
14. <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
15. <property name="show_sql">true</property>
16. <!-- C3P0 Connection Pooling Properties -->
17. <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0
ConnectionProvider</property>
18. <property name="hibernate.c3p0.min_size">1</property>
19. <property name="hibernate.c3p0.max_size">19</property>
20. <property name="hibernate.c3p0.timeout">120</property>
21. <property name="hibernate.c3p0.max_statements">10</property>
22. <mapping class="com.durgasoft.pojo.Employee"/>
23. </session-factory>
24. </hibernate-configuration>
1. c3p0-0.9.2.1.jar
2. hibernate-c3p0-4.3.11.Final.jar
3. mchange-commons-java-0.2.3.4.jar
Example:
Employee.java
161
1. package com.durgasoft.pojo;
2.
Page
3. import javax.persistence.Column;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
46. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
163
9.
10. import com.durgasoft.pojo.Employee;
11.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Provide Proxool connection pooling mechanism configurations in an xml file called as proxool
164
configuration file.
2. Configure proxool configuration file in hibernate configuration file.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It is an xml file, it includes all configuration details of proxool connection pooling mechanism which
includes driver class name, driver url, database user name, datyabase password, minimum
connection count, maximum connection count,......
To provide the above configuration details we have to use the following xml tags.
1. <proxool-config>
2. <proxool>
3. <alias>proxool_alias_name</alias>
4. <driver-class> driuver class name</driver-class>
5. <driver-url> driver url </driver-url>
6. <driver-properties>
7. <property name="prop_name" value="prop_value">
8. -----
9. </driver-properties>
10. <minimum-connection-count> min_size </minimum-connection-count>
11. <maximum-connection-count> max_size </maximum-connection-count>
12. </proxool>
13. </proxool-config>
EX:
proxool.xml
12. <maximum-connection-count>20</maximum-connection-count>
13. </proxool>
14. </proxool-config>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. hibernate.proxool.xml: It will take the name and location of proxool configuration file.
EX:
hibernate.cfg.xml
1. <hibernate-configuration>
2. <session-factory>
3. <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect </property>
4. <property name="hibernate.connection.provider_class">org.hibernate.connection.Proxool
ConnectionProvider</property>
5. <property name="hibernate.proxool.pool_alias">proxool</property>
6. <property name="hibernate.proxool.xml">proxool.xml</property>
7. <mapping class="com.durgasoft.hbn.pojo.Employee"/>
8. </session-factory>
9. </hibernate-configuration>
Note: To use this mechanism, we have to add the following JAR files in Hibernate Library.
1. proxool-0.8.3.jar
2. hibernate-proxool-4.3.11.Final.jar
EXample:
Employee.java
166
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
Page
4. import javax.persistence.Entity;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
44. }
45.
46. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
proxool.xml
Test.java
1. package com.durgasoft.test;
2.
168
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
Page
6. import org.hibernate.boot.registry.StandardServiceRegistry;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
JNDI [Java Naming And Directory Interface]: JNDI is a Middleware Service or an abstraction
provided by SUN Micreosystems as part of J2EE and which is implemented by all the Application
Servers vendors like Weblogic, JBOSS, Glassfish,.....
JNDI is existed inside the application Servers to provide any resource with Global Scope, that is,
JNDI will share any resource like "DataSource" to all the applications which are running in the
present application server.
In general, almost all the Application Servers are having their own Connection Pooling
mechanisms, if we want to use Application Servers provided Connection pooling mechanisms we
have to use the following steps.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
7. Select "DataSource".
8. Click on "New" button.
9. Select "Generic datasource".
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to get DataSource object from Weblogic Server provided JNDI into JDBC Application
then we ahve to use the following steps.
1. Create Hashtable object and put the following Weblogic Server provided JNDI configurations:
a) INITIAL_CONTEXT_FACTORY: It is a context from javax.naming.Context class , it will take
Server provided ContextFactory. Weblogic Server has provided a seperate ContextFactory
in the form of weblogic.jndi.ELInitialContextFactory.
b) PROVIDER_URL: It is a constant provided by javax.naming.Context class, it will take JNDI
server URL provided by Application Servers inorder to get Datasource object. Web logic
Server has provided JNDI url like "t3://localhost:7001"
EX:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: After getting Connection object we will provide our own JDBC Application logic inorder to
perform Database operations.
EX:
JDBC Application to use Weblogic Server privided Connection pooling Mechanism through JNDI.
1. package com.durgasoft.jdbc;
2. import java.sql.Connection;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import java.util.Hashtable;
6. import javax.naming.Context;
7. import javax.naming.InitialContext;
8. import javax.sql.DataSource;
9.
10. public class JdbcApp {
11.
12. public static void main(String[] args)throws Exception {
13. Hashtable<String, String> ht = new Hashtable<String, String>();
14. ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory
");
173
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Note: To run this example We have to keep ojdbc6.jar and weblogic.jar in build path.
weblogic.jar is existed in weblogic server
C:\Oracle\wlserver\server\lib\weblogic.jar
If we want to use Application Server provided DataSource object in Hibernate applications then
we have to provide the following properties configuration in hibernate configuration File.
1. hibernate.connection.provider_class:
In Hibernate, Every Connection Pooling mechanism will have a seperate Provider Class, this
property will take the Connection pooling mechanisms provider class which we defined by
hibernate. For Application Servers Connection Pooling mechanisms we have to provide
"org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl".
2. hibernate.connection.datasource:
This property will take JNDI name of the datasource object which we configured in application
Server.
3. hibernate.jndi.class:
It will take ConnectionFactory class provided by application Servers. Weblogic server will use
"weblogic.jndi.WLInitialContextFactrory" as value to this property.
4. hibernate.jndi.url:
This property will take JNDI url to get DataSource object , All application Servers has to provide a
174
seperate URL to access JNDI registry, Weblogic has provided "t3://localhost:7001" as JNDI url.
EX:
Page
1. <hibernate-configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
7. <property name="hibernate.jndi.url">t3://localhost:7001</property>
8. <mapping class="com.durgasoft.pojo.Employee"/>
9. </session-factory>
10. </hibernate-configuration>
Note: To run this example we have to keep weblogic.jar in Hibernate Lib and we must remove
ojdbc6.jar from Hibernate Lib.
Example:
Employee.java
1. package com.durgasoft.hbn.pojo;
2. import javax.persistence.Column;
3. import javax.persistence.Entity;
4. import javax.persistence.Id;
5.
6. @Entity
7. @Table(name="emp1")
8. public class Employee {
9. @Id
10. @Column(name="ENO")
11. private int eno;
12. @Column(name="ENAME")
13. private String ename;
14. @Column(name="ESAL")
15. private float esal;
16. @Column(name="EADDR")
17. private String eaddr;
18.
19. public int getEno() {
20. return eno;
21. }
175
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
14. </session-factory>
15.
16.
Page
17. </hibernate-configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.hbn.test;
2.
3. import java.util.Properties;
4.
5. import javax.naming.Context;
6. import javax.naming.InitialContext;
7.
8. import org.hibernate.Session;
9. import org.hibernate.SessionFactory;
10. import org.hibernate.Transaction;
11. import org.hibernate.boot.registry.StandardServiceRegistry;
12. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
13. import org.hibernate.cfg.Configuration;
14.
15. import com.durgasoft.hbn.pojo.Employee;
16.
17. public class Test {
18.
19. public static void main(String[] args)throws Exception {
20.
21. Configuration cfg = new Configuration();
22. cfg.configure();
23. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
24. builder = builder.applySettings(cfg.getProperties());
25. StandardServiceRegistry registry = builder.build();
26. SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
27. Session session = sessionFactory.openSession();
28.
29. Employee emp = new Employee();
30. emp.setEno(111);
31. emp.setEname("AAA");
32. emp.setEsal(5000);
33. emp.setEaddr("Hyd");
34. Transaction tx = session.beginTransaction();
35. session.save(emp);
36. tx.commit();
37. System.out.println("Employee Saved Successfully");
177
38. }
39. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate applications, if we want to perform manipulations over multiple records then we must
use the following features provided by Hibernate.
1. HQL[Hibernate Query Language]
2. Native SQL
3. Criteria API
Note: HQL is not suitable where we want to execute Database dependent sql queries
178
EX: PL/SQL procedures and functions are totally database dependent, where we are unable to
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Query object is able to store HQL query, to represent Query object Hibernate has provided a
predefined interface in the form of "org.hibernate.Query".
To get Query object we have to use the following method from org.hibernate.Session .
In hibernate applications, after getting Query object we have to set the custom properties like
providing fetch size , making the results as Cache results and read only results, providing start
record position and max no of records,..... To perform all these custom propertties we have to use
the following methods.
EX:
q.setFetchSize(10);
q.setCacheable(true);
q.setMaxResults(10);
q.setFirstResult(5);
q.setReadOnly(true);
q.setComment("Employee Details");
179
q.setTimeOut(10000);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It will execute HQl query and generate the results in the form of List.
EX:
It will execute HQL query and generate the results in the form of Iterator.
EX:
1. Iterator<Employee> it = query.iterate();
2. System.out.println("ENO\tENAME\tESAL\tEADDR");
3. System.out.println("------------------------------");
4. while(it.hasNext()) {
5. Employee e = (Employee)it.next();
6. System.out.print(e.getEno()+"\t");
7. System.out.print(e.getEname()+"\t");
8. System.out.print(e.getEsal()+"\t");
9. System.out.println(e.getEaddr());
10. }
It able to execute HQl query and generate the results in form of ScrollableResults, which is
same as ScrollableResultSet object , it allows to read data in both forward and backward
directions.
180
Note: In the case of ScrollableResults we are able to use the following methods inorder to retrive
data.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
It will execute HQl query and it will return only one result, if more than one result is
identified then it will rise an Exception.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It can be used to perform the database operations like insert, update, delete,..... and it will
generate rowCount value.
EX:
1. Query query = session.createQuery("update Employee set esal = esal + 500 where esal <
10000");
2. Transaction tx = session.beginTransaction();
3. int rowCount = query.executeUpdate();
4. tx.commit();
5. System.out.println("Records Updated :"+rowCount);
EX:
Example:
Employee.java
1. package com.durgasoft.pojo;
182
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
Page
5. import javax.persistence.Id;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
45.
46.
47. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import java.util.Iterator;
4. import java.util.List;
5.
6. import org.hibernate.Query;
7. import org.hibernate.ScrollableResults;
8. import org.hibernate.Session;
9. import org.hibernate.SessionFactory;
10. import org.hibernate.boot.registry.StandardServiceRegistry;
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
12. import org.hibernate.cfg.Configuration;
13.
14. import com.durgasoft.pojo.Employee;
15.
16. public class Test {
17.
18. public static void main(String[] args) throws Exception{
184
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
65. System.out.print(e.getEname()+"\t");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="emp1")
10. public class Employee {
11. @Id
12. @Column(name="ENO")
13. private int eno;
14. @Column(name="ENAME")
15. private String ename;
16. @Column(name="ESAL")
17. private float esal;
18. @Column(name="EADDR")
19. private String eaddr;
20.
21. public int getEno() {
22. return eno;
23. }
24. public void setEno(int eno) {
25. this.eno = eno;
26. }
27. public String getEname() {
28. return ename;
29. }
30. public void setEname(String ename) {
31. this.ename = ename;
32. }
33. public float getEsal() {
34. return esal;
35. }
187
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.Java:
1. package com.durgasoft.test;
2.
3. import java.util.Iterator;
4. import java.util.List;
5.
6. import org.hibernate.Query;
7. import org.hibernate.ScrollableResults;
8. import org.hibernate.Session;
9. import org.hibernate.SessionFactory;
188
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In HQL , we are able to use "insert" query to copy multiple records from one table to another table
, not to insert a record into the database table directly.
EX:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee1.java
1. package com.durgasoft.pojo;
2.
3. public class Employee1 {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. this.esal = esal;
26. }
27. public String getEaddr() {
28. return eaddr;
29. }
30. public void setEaddr(String eaddr) {
31. this.eaddr = eaddr;
32. }
33.
34.
35. }
190
Employee2.java
Page
1. package com.durgasoft.pojo;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee1.hbm.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee2.hbm.xml
hibernate.cfg.xml
15. </hibernate-configuration>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.test;
2.
3. import org.hibernate.Query;
4. import org.hibernate.Session;
5. import org.hibernate.SessionFactory;
6. import org.hibernate.Transaction;
7. import org.hibernate.boot.registry.StandardServiceRegistry;
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9. import org.hibernate.cfg.Configuration;
10.
11. public class Test {
12.
13. public static void main(String[] args)throws Exception {
14. Configuration config = new Configuration();
15. config.configure();
16. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
17. builder = builder.applySettings(config.getProperties());
18. StandardServiceRegistry registry = builder.build();
19. SessionFactory sessionFactory = config.buildSessionFactory(registry);
20. Session session = sessionFactory.openSession();
21. Query query = session.createQuery("insert into Employee2(eno,ename,esal,eaddr)sel
ect e.eno,e.ename,e.esal,e.eaddr from Employee1 as e");
22. Transaction tx = session.beginTransaction();
23. int rowCount = query.executeUpdate();
24. tx.commit();
25. System.out.println("Employee details are transfered from emp1 to emp2");
26. session.close();
27. sessionFactory.close();
28. }
29. }
The above Example with single mapping file with two pojo classes configuration
Example:
Employee1.java
193
1. package com.durgasoft.pojo;
2.
3. public class Employee1 {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee2.java
1. package com.durgasoft.pojo;
2.
3. public class Employee2 {
4. private int eno;
5. private String ename;
194
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Query;
4. import org.hibernate.Session;
5. import org.hibernate.SessionFactory;
6. import org.hibernate.Transaction;
7. import org.hibernate.boot.registry.StandardServiceRegistry;
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9. import org.hibernate.cfg.Configuration;
10.
11. public class Test {
12.
13. public static void main(String[] args)throws Exception {
14. Configuration config = new Configuration();
196
15. config.configure();
16. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
17. builder = builder.applySettings(config.getProperties());
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee1.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="emp1")
10. public class Employee1 {
11. @Id
12. @Column(name="ENO")
13. private int eno;
14. @Column(name="ENAME")
15. private String ename;
16. @Column(name="ESAL")
17. private float esal;
18. @Column(name="EADDR")
19. private String eaddr;
20.
21. public int getEno() {
22. return eno;
197
23. }
24. public void setEno(int eno) {
25. this.eno = eno;
Page
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee2.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="emp2")
10. public class Employee2 {
11. @Id
12. @Column(name="ENO")
13. private int eno;
14. @Column(name="ENAME")
15. private String ename;
198
16. @Column(name="ESAL")
17. private float esal;
18. @Column(name="EADDR")
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
9. <property name="connection.password">durga</property>
10. <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Query;
4. import org.hibernate.Session;
5. import org.hibernate.SessionFactory;
6. import org.hibernate.Transaction;
7. import org.hibernate.boot.registry.StandardServiceRegistry;
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9. import org.hibernate.cfg.Configuration;
10.
11. public class Test {
12.
13. public static void main(String[] args)throws Exception {
14. Configuration config = new Configuration();
15. config.configure();
16. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
17. builder = builder.applySettings(config.getProperties());
18. StandardServiceRegistry registry = builder.build();
19. SessionFactory sessionFactory = config.buildSessionFactory(registry);
20. Session session = sessionFactory.openSession();
21. Query query = session.createQuery("insert into Employee2(eno,ename,esal,eaddr)sel
ect e.eno,e.ename,e.esal,e.eaddr from Employee1 as e");
22. Transaction tx = session.beginTransaction();
23. int rowCount = query.executeUpdate();
24. tx.commit();
25. System.out.println("Employee details are transfered from emp2 to emp1");
26. session.close();
27. sessionFactory.close();
200
28. }
29. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. Clauses:
These are building blocks to HQL queries, which are able to specify POJO classes property
names, conditional expressions,.....
EX:
from
select
where
order by
group by
having
----
----
1. from:
It can be used to specify POJO class names and their alias names in HQL queries.
Syntax:
EX:
From Employee
FROM Employee
from Employee e
From Employee AS e
201
2. select:
This clause can be used to specify POJO class properties names inorder to retrive individual
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Syntax:
EX:
3. Where clause:
In HQL, where clause can be used to provide a particular conditional expression inorder to retrive
the results as per the condition.
Syntax:
EX:
6. for(Object o: obj) {
7. System.out.print(o+"\t");
8. }
Page
9. System.out.println();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. Order by:
It can be used to retrive all results either in ascending order or in descending order w.r.t a
particular column. in HQL, bydefault, all results are generated in Ascending order only.
Syntax:
EX:
5. group by:
This clause can be used to specify groups over the retrived results w.r.t a particular column.
Note: In HQL queries, we are able to implement group by clause with the combination of
aggregate functions only.
Syntax:
EX:
ename");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
6.having:
The main intention of having clause is to implement a conditional expression while including
elements in groups as per group by clause.
Syntax:
EX:
2. Aggregate Functions:
The main intention of Aggregate functions is to provide small arithmetic calculations over the
results.
EX:
1. count: It able to count the no of results are generated from HQl query and the resultent count
value is generated in the form of java.lang.Long type.
EX:
5. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2.sum: It able to perform addition operation over the results which are generated from HQl query.
EX:
3. min: It able to get min value over all the results which are generated from HQl query.
EX:
4. max: It able to get max value over all the results which are generated from HQl query.
EX:
5. avg: It able to generate average value over all the generated results from HQL query.
EX:
5. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of Generic Expressions is to provide expressions in HQL queries inorder to
perform simple Arithmetic calculations, comparisions,......
To provide generic expressions in HQL queries we have to use the following elements.
EX:
EX:
d)Scalar Functions:
EX:
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
e) IN:It will be used along with where clause to specify a list of values inorder to retrive matched
results.
EX:
f) BETWEEN : It able to specify min value and max value inorder to retrive the results which are
between the specified min value and max value.
EX:
7. System.out.print(o+"\t");
8. }
9. System.out.println();
Page
10. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
g) LIKE: It able to provide a particular pattern in HQL query inorder to retrive matched results.
EX:
h) IS NULL: It able to retrive all the results from database table w.r.t a particular column whose
value is null.
EX:
i) IS NOT NULL: It able to retrive all the results from database table w.r.t a particular column
whose value is not null.
EX:
208
3. System.out.println("ENO\tENAME\tESAL\tEADDR");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. Parameters
The main intention of parameters in HQL queries is to take dynamic values in HQL queries.
In HQL, there are two types of parameters
1. Positional parameters
2. Named Parameters
1. Positional parameters:
Note: In JDBC, positional parameter indexes will start from 1 , but, in HQL parameters indexes
will start from 0.
EX:
9. }
10. System.out.println();
11. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
2. Named Parameters:
These parameters are represented in the form of ':Param_Name' in HQL queries, after providing
named parameters in HQL query we have to set values to named parameters, for this, we have to
use the following method.
public void setXXX(String param_name, xxx value)
Where xxx may be byte, short, int, String,.....
Note: in HQL queries, we are able to provide more than one named parameters.
EX:
8. for(Object o: val) {
9. System.out.print(o+"\t");
10. }
Page
11. System.out.println();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate applications we are able to provide both positional parameters and named
parameters with in a single HQL query, but, first we have to provide all positional patameters after
that only we have to provide named parameters, we must not provide any positional parameter
after named parameter.
EX:
If we provide named parameter before positional parameter ion HQL query then we are able to get
the following error or Exception.
ERROR: cannot define positional parameter after any named parameters have been defined
5. Subqueries
EX:
4. System.out.println("---------------------------------");
5. for(Object[] val : list) {
6. for(Object o: val) {
Page
7. System.out.print(o+"\t");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
6. Pagination
The process of displying results in more than one page is called as Pagination.
Displaying 3 results in a page like three pages out of 9 results is called as "Pagination".
Example:
form.html
DisplayServlet.java
1. package com.durgasoft.servlets;
212
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
Page
5. import java.util.List;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
42. }
43.
44. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.service;
2.
3. import java.util.List;
4.
5. import org.hibernate.Query;
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8.
9. import com.durgasoft.beans.Employee;
10. import com.durgasoft.util.HibernateUtil;
11.
12. public class EmployeeService {
13. List<Employee> list;
14. SessionFactory sessionFactory;
15. Session session;
16. Query query;
17. public EmployeeService() {
18. try {
19. sessionFactory = HibernateUtil.getSessionFactory();
20. session = sessionFactory.openSession();
21. query = session.createQuery("from Employee");
22. query.setMaxResults(3);
23. } catch (Exception e) {
24. e.printStackTrace();
25. }
26. }
27. public List<Employee> getEmployees(int label){
28. try {
29. if(label == 1) {
30. query.setFirstResult(0);
31. }
32. if(label == 2) {
33. query.setFirstResult(3);
34. }
35. if(label == 3) {
36. query.setFirstResult(6);
37. }
214
41. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
HibernateUtil.java
1. package com.durgasoft.util;
2.
3. import org.hibernate.SessionFactory;
4. import org.hibernate.boot.registry.StandardServiceRegistry;
5. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
6. import org.hibernate.cfg.Configuration;
7.
8. public class HibernateUtil {
9. private static SessionFactory sessionFactory;
10. static {
11. try {
12. Configuration config = new Configuration();
13. config.configure();
14. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
15. builder = builder.applySettings(config.getProperties());
16. StandardServiceRegistry registry = builder.build();
17. sessionFactory = config.buildSessionFactory(registry);
18. } catch (Exception e) {
19. e.printStackTrace();
20. }
21. }
22. public static SessionFactory getSessionFactory() {
23. return sessionFactory;
24. }
25. }
Employee.java
1. package com.durgasoft.beans;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
215
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
Page
8. @Entity
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
web.xml
7. <welcome-file>index.jsp</welcome-file>
8. <welcome-file>default.html</welcome-file>
9. <welcome-file>default.htm</welcome-file>
Page
10. <welcome-file>default.jsp</welcome-file>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. Native SQL:
In Hibernate applications, by using Session we are able to perform database operations on
only single record, but, if we want to perform database operations over multiple records
then we have to use HQL, but, HQL is not providing environment for Database dependent
native operations.
HQL is is able to provide support for DML[insert, update, delete, select] operations, but, it
has not provided environment for DDL[create, alter and drop] queries.
HQL is not supporting stored procedures and functions kind of database dependent native
operations.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To execute Sql Query represent by SqlQuery object we have to use the following methods.
Entity SQLQueries are database dependent sql queries, it can be used to retrive the complete
records in the form of an Entity. It will include '*' notation to get all columns data in a record in the
form of Entity object.
Before executing the query we have to provide entity type to SqlQuery object inorder to store
results, for this, we have to use the following method.
EX: query.addEntity(com.durgasoft.hibernate.Employee.class);
Example:
Employee.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
219
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
Page
8. @Entity
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import java.util.List;
4.
5. import org.hibernate.SQLQuery;
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8. import org.hibernate.boot.registry.StandardServiceRegistry;
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
10. import org.hibernate.cfg.Configuration;
11.
12. import com.durgasoft.pojo.Employee;
13.
14. public class Test {
15.
16. public static void main(String[] args) throws Exception{
17. Configuration cfg = new Configuration();
18. cfg.configure();
19. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
20. builder = builder.applySettings(cfg.getProperties());
21. StandardServiceRegistry registry = builder.build();
221
25. query.addEntity(com.durgasoft.pojo.Employee.class);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Positional parameters are represented in the form of '?' s , we are able to provide more
than one positional parameter with in a single sql query. To set values to the positional
parameters we have to use the following method from SqlQuery.
Names parameters are represented in the form of ':name' , we are able to provide more
than one named parameter in native sql query. To provide values to the named parameters
we have to use the following method.
In a single native sql query, we are able to provide both positional parameters and named
parameters, but, fiorst we must provide all positional parameters after that only we have to
provide named parameters, we must not provide any positional parameter after named
parameter.
EX:
222
3. query.setFloat("max_Sal", 8000);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In the above approach, we have declare sql query directly in client application, it is
available upto the present client application only, it is not available to other client
applications, this approach is called as "Programatic Approach".
In Hibernate applications, if we want use the same sql query in more than one client
application then programatic approach is nit suggetible, at each and every client application
we have to hardcode the query, it is not suggestible, to overcome this problem we have to
use "Declarative approach".
In Declarative approach, we will declare native sql query in mapping file along with a
particular logical name and we will get that query from mapping file on the basis of the
name, this type of sql queries are called as Named SQL Queries.
To declare sql query in mapping file we have to use the following tags in mapping file.
1. <hibernate-mapping>
2. -----
3. <sql-query name="--">
4. <return class="--">
5. ---sql query------
6. </sql-query>
7.
8. </hibernate-mapping>
'name' attribute in <sql-query> tag will take logical name to the query.
<return> tag will take a pojo class name with 'class' attribute inorder to get results in the form of
POJO objects.
223
To get named sql query from mapping file to hibernate Client Application we have to use the
following method.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Declartive native sql query we are able to provide both positional parameters and named
parameters depending on the requirement.
Note: In Native SQL queueris we are unable to use '<' symbol in mapping file, because, '<' symbol
is treated as starting tag form xml tags, inplace of '<' symbol we have to use '<' symbol in
mapping file.
EX:
Employee.java
1. package com.durgasoft.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public int getEno() {
10. return eno;
11. }
12. public void setEno(int eno) {
13. this.eno = eno;
14. }
15. public String getEname() {
16. return ename;
17. }
18. public void setEname(String ename) {
19. this.ename = ename;
20. }
21. public float getEsal() {
22. return esal;
23. }
24. public void setEsal(float esal) {
25. this.esal = esal;
26. }
27. public String getEaddr() {
224
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
hibernate.cfg.xml
15. </session-factory>
16. </hibernate-configuration>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.test;
2.
3. import java.util.List;
4.
5. import org.hibernate.Query;
6. import org.hibernate.SQLQuery;
7. import org.hibernate.Session;
8. import org.hibernate.SessionFactory;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11. import org.hibernate.cfg.Configuration;
12.
13. import com.durgasoft.pojo.Employee;
14.
15. public class Test {
16.
17. public static void main(String[] args) throws Exception{
18. Configuration cfg = new Configuration();
19. cfg.configure();
20. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
21. builder = builder.applySettings(cfg.getProperties());
22. StandardServiceRegistry registry = builder.build();
23. SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
24. Session session = sessionFactory.openSession();
25. Query query = session.getNamedQuery("sql_Query");
26. query.setFloat(0, 6000);
27. query.setFloat("max_Sal", 8000);
28. List<Employee> list = query.list();
29. System.out.println("ENO\tENAME\tESAL\tEADDR");
30. System.out.println("---------------------------------");
31. for(Employee e : list) {
32. System.out.print(e.getEno()+"\t");
33. System.out.print(e.getEname()+"\t");
34. System.out.print(e.getEsal()+"\t");
35. System.out.print(e.getEaddr()+"\n");
36. }
37.
226
38. session.close();
39. sessionFactory.close();
40. }
Page
41. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It is a native SQL query, it able to retrive records data from individual columns and it able to
generate results in the form of Object[].
To represent scalar sql queries we will use org.hibernate.SqlQuery, to get SqlQuery object we will
use the following method.
Example:
Employee.java
1. package com.durgasoft.pojo;
2. public class Employee {
3. private int eno;
4. private String ename;
5. private float esal;
6. private String eaddr;
7.
8. public int getEno() {
9. return eno;
10. }
11. public void setEno(int eno) {
12. this.eno = eno;
13. }
14. public String getEname() {
15. return ename;
16. }
17. public void setEname(String ename) {
18. this.ename = ename;
19. }
20. public float getEsal() {
21. return esal;
22. }
23. public void setEsal(float esal) {
227
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
hibernate.cfg.xml
14. </session-factory>
15. </hibernate-configuration>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.test;
2.
3. import java.util.List;
4.
5. import org.hibernate.Query;
6. import org.hibernate.SQLQuery;
7. import org.hibernate.Session;
8. import org.hibernate.SessionFactory;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11. import org.hibernate.cfg.Configuration;
12.
13. public class Test {
14.
15. public static void main(String[] args) throws Exception{
16. Configuration cfg = new Configuration();
17. cfg.configure();
18. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
19. builder = builder.applySettings(cfg.getProperties());
20. StandardServiceRegistry registry = builder.build();
21. SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
22. Session session = sessionFactory.openSession();
23. SQLQuery query = session.createSQLQuery("select eno, ename, esal, eaddr from em
p1");
24. List<Object[]> list = query.list();
25. System.out.println("ENO\tENAME\tESAL\tEADDR");
26. System.out.println("---------------------------------");
27. for(Object[] obj: list) {
28. System.out.println(obj[0]+"\t"+obj[1]+"\t"+obj[2]+"\t"+obj[3]);
29. }
30.
31. session.close();
32. sessionFactory.close();
33. }
34. }
In Scalar SQL Queries we are able to provide both Positional parameters and Named
229
parameters ,but, first we must provide positional parameters after that only we must provide
named parameters.
If we provide positional parameters and named parameters in sql query then we must
Page
provide values to these parameters , for this, we must use the following methods.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate applications, we are able to provide scalar sql queries in diclarative manner in
mapping file. To declare scalar sql queries in mapping file we have to use the following syntax.
1. <hibernate-mapping>
2. ------
3. <sql-query name="--">
4. <return-scalar column="--" type="--"/>
5. -----
6. ------scalar sql query ------
7. </sql-query>
8. -----
9. </hibernate-mapping>
where <return-scalar> tag is able to represent a particular scalar[column name], for which, we
have to declare data type by using 'type' attribute.
Note: In Named scalar sql query we are able to provide both positional parameters and named
parameters, first we have to provide positional parameters after that we have to provide named
parameters.
Example:
Employee.java
230
1. package com.durgasoft.pojo;
2.
3. public class Employee {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
9. <property name="esal"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import java.util.List;
4.
5. import org.hibernate.Query;
6. import org.hibernate.SQLQuery;
7. import org.hibernate.Session;
232
8. import org.hibernate.SessionFactory;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Database related applications, first we will define database logic at JAVA applications adn we
will transfer that logic to databases inorder to execute, If we have any requirement like to execute
a particular database logic frequently then it is suggestible to use Stored Procedures and
functions in database related applications.
In the above context, define the frequently executed database logic at the database side in the
form of Stored Procedures and functions, not at java side and prepare stored procedure call and
function call at java application and send that procedure or function call to Database when we
233
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ANS:
Syntax:
Syntax:
1)IN Type Parameter: It will get value from Procedure/function call to procedure body or function
body.
EX: no IN number
2)OUT Type Parameter: It will get value from Procedure/function body to procedure/function call.
EX: sal OUT float
234
3)INOUT Type parameter: It is acting as both IN type parameter and OUT type parameter.
EX: sal INOUT float
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use Stored Procedures and Functions in Hibernate applications then we have to use
the following steps.
1. Define Stored Procedure orr Function at Database side.
2. Configure the respective Stored procedure/Function call in hibernate mapping file.
3. In Client Application, create Query object with the procedure call or Function call logical
name.
4. Execute Procedure or Function call.
EX:
Procedure at DB:
Employee.java
1. package com.durgasoft.pojo;
2. public class Employee {
3. private int eno;
4. private String ename;
5. private float esal;
6. private String eaddr;
7.
8. public int getEno() {
9. return eno;
10. }
11. public void setEno(int eno) {
12. this.eno = eno;
13. }
14. public String getEname() {
235
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
hibernate.cfg.xml
5. <hibernate-configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import java.util.List;
4.
5. import org.hibernate.Query;
6. import org.hibernate.SQLQuery;
7. import org.hibernate.Session;
8. import org.hibernate.SessionFactory;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11. import org.hibernate.cfg.Configuration;
12.
13. import com.durgasoft.pojo.Employee;
14.
15. public class Test {
16.
17. public static void main(String[] args) throws Exception{
18. Configuration cfg = new Configuration();
19. cfg.configure();
20. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
21. builder = builder.applySettings(cfg.getProperties());
22. StandardServiceRegistry registry = builder.build();
23. SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
24. Session session = sessionFactory.openSession();
237
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Function at Database:
Function created.
Employee.java
1. package com.durgasoft.pojo;
2. public class Employee {
3. private int eno;
4. private String ename;
5. private float esal;
6. private String eaddr;
7.
8. public int getEno() {
238
9. return eno;
10. }
11. public void setEno(int eno) {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
15. </sql-query>
16. </hibernate-mapping>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2. import java.util.List;
3. import org.hibernate.Query;
4. import org.hibernate.SQLQuery;
5. import org.hibernate.Session;
6. import org.hibernate.SessionFactory;
7. import org.hibernate.boot.registry.StandardServiceRegistry;
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9. import org.hibernate.cfg.Configuration;
10.
11. import com.durgasoft.pojo.Employee;
12.
13. public class Test {
14.
15. public static void main(String[] args) throws Exception{
16. Configuration cfg = new Configuration();
17. cfg.configure();
240
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. Criterion API:
By using Session interface methods like save(), persist(), update(), delete(),..... we are able
to perform single record manipulation, but, if we want to perform manipulations over
multiple records then we must go for HQL, Native SQL and Criterion API.
Where HQL is a powerfull, Object Oriented and Database INdependent Query language
provided by Hibernate, but, HQL is not providing environment to perform DDL kind of
operations and it is not supporting database dependent native operations like invoking
stored procedures and functions,.....
To overcome the above problem with HQL we will use "Native SQL", in case of Native SQL
, we have to write database dependent SQL queries directly, but, it is against to Hibernate,
as per the Hibernate view we must not write database dependent sql queries in JAVA
applications.
In Hibernate applications, to avoid totally query langugaes like SQL and HQL,....and to
provide the complete dPersistence logic in the form of JAVA code we must use "Criterion
API".
In the case of Criterion API, we will define persistence logic by using JAVA code only,
where the required predefined library was provided by Hibernate in the form of
241
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Criteria object is a central object in Critera API, it able to manage HQl query repersentation
internally and it has provided predefined methods to defined query logic.
To create Criteria object we have to use the following method from Session.
2. Prepare Criterion objects and add that Criterion objects to Criteria object:
To create Criterion object we have to use the following methods from "org.hibernate.Restrictions"
class.
public static Criterion isEmpty(String property)
public static Criterion isNotEmpty(String property)
public static Criterion isNull(String property)
public static Criterion isNotNull(String property)
public static Criterion in(String property, Object[] obj)
public static Criterion in(String property, Collection c)
public static Criterion between(String property, Object min_Val, Object max_Val)
public static Criterion between(String property, Object[] obj)
public static Criterion eq(String property, Object val)
public static Criterion ne(String property, Object val)
public static Criterion lt(String property, Object val)
public static Criterion le(String property, Object val)
public static Criterion gt(String property, Object val )
public static Criterion ge(String property, Object val)
-----
-----
To add a particular Criterion object to Criteria object we have to use the following method.
public void add(Criterion c)
EX:
242
c.add(c2);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
The main intention of Projection object is to represent a single POJO class property.
To get Projection object with a particular Property name we have to use the following method from
"Projections" class.
public static Projection projection(String pro_Name)
To create ProjectionList object we have to use the following method from Projections class.
public static ProjectionList projectionList()
To add Projection object to ProjectionList we have to use the following method from ProjectionList
class.
public void add(Projection p)
Ex:
ProjectionList pl = Projections.projectionList();
pl.add(Projections.property("eno"));
pl.add(Projections.property("ename"));
pl.add(Projections.property("esal"));
pl.add(Projections.property("eaddr"));
c.setProjection(pl);
EX: With the above , Criteria object is able to prepare HQL query internally like below.
"select eno, ename, esal, eaddr from Employee where esal >=6000 and esal<=90000".
To represent a particular Order over the results, we have to use either asc(-) or desc(-) methods
from "Order" class.
243
To add Order object to Criteria object we have to use the following method.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
Order o = Order.desc("ename");
c.addOrder(o);
Note: With this, Criteria object is able to create HQl query like
"select eno, ename, esal, eaddr from Employee where esal >=6000 and esal<=90000 order by
desc(ename)"
To execute database logic existed in Criteria object we have to use the following methods.
EX:
244
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Employee.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="emp1")
10. public class Employee {
11. @Id
12. @Column(name="ENO")
13. private int eno;
14. @Column(name="ENAME")
15. private String ename;
16. @Column(name="ESAL")
17. private int esal;
18. @Column(name="EADDR")
19. private String eaddr;
20.
21. public int getEno() {
22. return eno;
23. }
24. public void setEno(int eno) {
25. this.eno = eno;
245
26. }
27. public String getEname() {
28. return ename;
Page
29. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
246
1. package com.durgasoft.test;
2.
Page
3. import java.util.List;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
43.
44. Order order = Order.desc("ename");
45. c.addOrder(order);
Page
46.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
248
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
If we want to use Filters in Hibernate applications we have to use the following steps.
sql>create table emp(ENO number primary key, ENAME varchar2(10), ESAL float, EADDR
varchar2(10), ETYPE varchar2(10));
Here "ETYPE" is Filter parameter column, by using this Filter parameter column only we are able
to prepare Filter condition inorder to filter the results.
2) Define Filte in mapping File:
To define Filter in mapping file we have to use the following xml tags in mapping file.
1. <hibernate-mapping>
2. -----
3. <class name="--" table="--">
4. ------
5. <filter name="--" condition="--"/>
6. </class>
7. <filter-def name="--">
8. <filter-param name="--" type="--"/>
9. </filter-def>
10. ----
11. </hibernate-mapping>
Where <filder-def> tag can be used to define a filter in Hibernate mapping file.
Where "name" attribute in <filter-def> tag is able to take logical name of the filter.
Where <filter-param> tag is a chaild tag to <filter-def> tag , it will define a particular filter
parameter.
Where "name" attribute in <filter-param" tag will take name of the filter parameter.
Where "type" attribute in <filter-param> tag will take java type like "string", "byte", "int",....
Where "<filter>" tag under <class> tag is able to configure Filter to mapping.
249
Where "name" attribute in <filter> tag is able to take logical of the filter which we have
defined in <filter-def>" tag.
Where "condition" attribute in <filter> tag is able to define condition inorder to filter the
Page
results.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To set values to the Filter parameter we will use the following method.
public void setParameter(String filter_Name, xxx value)
Where xxx may be byte, short, int,.....
Example:
Employee.java
1. package com.durgasoft.pojo;
2. public class Employee {
3. private int eno;
4. private String ename;
5. private float esal;
6. private String eaddr;
7. private String etype;
250
8.
9. public String getEtype() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
9. <property name="esal"/>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import java.util.List;
4. import java.util.Scanner;
5.
6. import org.hibernate.Filter;
7. import org.hibernate.Query;
8. import org.hibernate.Session;
9. import org.hibernate.SessionFactory;
252
13.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In the above context, both Object Oriented Data Model and relational Data model are
having their own conventions to represent data, these different conventions will create
mismatches between data models, it will reduce data persistency in enterprise applications.
Hibernate is one of the ORM implementation , it has provided "Hibernate Mappings" feature
to resolve mismatches between data models. To resolve mismatches between data
models, Hibernate has provided the following mappings.
1. Basic OR Mapping:
It is normal mapping between a class, an ID property, a normal property from Object Oriented
data model and a table, a primary key column and normal columns.
2. Component Mapping:
IN Hibernate applications, Component Mapping will provide solution for Granualarity Mismatch.
In Component mapping, we will define a component property inorder tyo refer multiple columns in
a Database table.
To configure component property in hibernate applications we will use the following XML tags.
254
1. <hibernate-mapping>
2. <class name="--" table="--">
3. -------
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where "<component>" tag will take Component class and its reference variable
declaration, where "name" attribute will take component property reference variable and
"class" attribute will take fully qualified name of the respective component class.
Example:
Account.java
1. package com.durgasoft.pojo;
2.
3. public class Account {
4. private String accNo;
5. private String accName;
255
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Address.java
1. package com.durgasoft.pojo;
2.
3. public class Address {
4. private String pno;
5. private String street;
6. private String city;
7. public String getPno() {
8. return pno;
9. }
10. public void setPno(String pno) {
11. this.pno = pno;
12. }
13. public String getStreet() {
14. return street;
15. }
16. public void setStreet(String street) {
17. this.street = street;
256
18. }
19. public String getCity() {
20. return city;
Page
21. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. public class Employee {
4. private int eno;
5. private String ename;
6. private float esal;
7. private Account eacc;
8. private Address eaddr;
9.
10. public int getEno() {
11. return eno;
12. }
13. public void setEno(int eno) {
14. this.eno = eno;
15. }
16. public String getEname() {
17. return ename;
18. }
19. public void setEname(String ename) {
20. this.ename = ename;
21. }
22. public float getEsal() {
23. return esal;
24. }
25. public void setEsal(float esal) {
26. this.esal = esal;
27. }
28. public Account getEacc() {
29. return eacc;
30. }
31. public void setEacc(Account eacc) {
257
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
hibernate.cfg.xml
7. <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
8. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
9. <property name="connection.user">system</property>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.Account;
11. import com.durgasoft.pojo.Address;
12. import com.durgasoft.pojo.Employee;
13.
14. public class Test {
15.
16. public static void main(String[] args){
17. SessionFactory sessionFactory = null;
18. Session session = null;
19. try {
20. Configuration cfg = new Configuration();
21. cfg.configure();
22. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
23. builder = builder.applySettings(cfg.getProperties());
24. StandardServiceRegistry registry = builder.build();
25. sessionFactory = cfg.buildSessionFactory(registry);
26. session = sessionFactory.openSession();
27.
28. Account acc = new Account();
29. acc.setAccNo("a111");
30. acc.setAccName("AAA");
259
31. acc.setAccType("Savings");
32.
33. Address addr = new Address();
Page
34. addr.setPno("23/3t");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To provide component mapping in Hibernate applications we will use the following annotations
from javax.persistence package.
@Embeddable
@Embedded
Example:
Account.java
1. package com.durgasoft.pojo;
2.
260
3. import javax.persistence.Column;
4. import javax.persistence.Embeddable;
5. import javax.persistence.Entity;
Page
6.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Address.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Embeddable;
5. import javax.persistence.Entity;
261
6.
7. @Entity
8. @Embeddable
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Embedded;
5. import javax.persistence.Entity;
6. import javax.persistence.Id;
7. import javax.persistence.Table;
8.
9. @Entity
262
10. @Table(name="emp3")
11. public class Employee {
12. @Id
Page
13. @Column(name="ENO")
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
53. }
54.
55.
Page
56. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.Java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.Account;
11. import com.durgasoft.pojo.Address;
12. import com.durgasoft.pojo.Employee;
13.
14. public class Test {
15.
16. public static void main(String[] args){
17. SessionFactory sessionFactory = null;
18. Session session = null;
264
19. try {
20. Configuration cfg = new Configuration();
21. cfg.configure();
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. Inheritance Mapping:
In Enterprise Applications, we are able to use the data models like Object Oriented Data
Model, Relational Data Model,...In general, Front-End applications are able to use Object
265
Oriented Data Model to represent data and Back-End Systems are able to use Relational
Data Model to represent data.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Relational data Model, we will use different approaches to manage inheritance kind of
features at databases like maintaining all the classes properties in a single table or defining
a seperate table for each and every class and providing PK-FK relation between these
tables,.....
In both the above cases, approaches are different to achive inheritance kind of feature, it
will provide Sub types mismatches between data models, it will reduce data persistencey in
enterprise applications.
In the above context, to improve data persistency in enterprise applications we have to use
ORM implementation, Hibernate is one of the ORM implementation, it has provided the
following three strategies to resolve inheritance mismatch.
In this mechanism, when we store any sub class object then data must be stored in single
table in the respective columns, if data is not available for any column then null values will
be stored in the respective columns.
If we want to use Table Per Class Hierarchy in Hibernate applications then we have to use the
following steps.
1) Prepare all java classes which we want to keep in Inheritance
EX:
Account.java
6. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeAccount.java
2) Create a table in Database with a set of columns which are representinig all properties of
the classes which are existed in inheritance and discriminator column:
SQL> create table account(ACCNO varchar2(5) primary key, ACCNAME varchar2(5), accType
varchar2(10), SID varchar2(5), SBRANCH varchar2(5), SMARKS number(3), EID varchar2(5),
ESAL float, EADDR varchar2(10), TYPE varchar2(10));
Where the purponse Discriminator column is to specify which sub class object data is represented
by the present record.
1. <hibernate-mapping>
2. <class name="--" class="--">
3. ----
4. <discrimantor column="--"/>
5. ----
6. <subclass name="--" discriminator-value="--">
7. -----
8. </subclass>
267
9. ----
10. </class>
11. </hibernate-mapping>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where "<subclass> tag is able to configure a single sub class and its properties, where
"name" attribute will take fully qualified name of the respective sub class, where
"discriminator-value" attribute will provide the exact discriminator value inorder to insert or
retrive sub class object data.
EX:
1. <hibernate-mapping>
2. <class name="com.durgasoft.pojo.Account" table="account">
3. <id name="accNo" column="ACCNO"/>
4. <discriminator column="TYPE" type="string"/>
5. <property name="accName" column="ACCNAME"/>
6. <property name="accType" column="ACCTYPE"/>
7.
8. <subclass name="com.durgasoft.pojo.StudentAccount" discriminator-value="std">
9. <property name="sid" column="SID"/>
10. <property name="sbranch" column="SBRANCH"/>
11. <property name="smarks" column="SMARKS"/>
12. </subclass>
13.
14. <subclass name="com.durgasoft.pojo.EmployeeAccount" discriminator-
value="emp">
15. <property name="eid" column="EID"/>
16. <property name="esal" column="ESAL"/>
17. <property name="eaddr" column="EADDR"/>
18. </subclass>
19. </class>
20. </hibernate-mapping>
4) In client application, Create Sub class objects with the data and perform the required
database operation:
5. sa.setAccNo("a1");
6. sa.setAccName("AAA");
7. sa.setAccType("Savings");
Page
8. sa.setSid("S1");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
269
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Account.java
1. package com.durgasoft.pojo;
2.
3. public class Account {
4. private String accNo;
5. private String accName;
6. private String accType;
7.
8. public String getAccNo() {
9. return accNo;
10. }
11. public void setAccNo(String accNo) {
12. this.accNo = accNo;
13. }
14. public String getAccName() {
15. return accName;
16. }
17. public void setAccName(String accName) {
18. this.accName = accName;
19. }
20. public String getAccType() {
21. return accType;
22. }
23. public void setAccType(String accType) {
24. this.accType = accType;
25. }
26.
27.
28. }
StudentAccount.java
1. package com.durgasoft.pojo;
2.
3. public class StudentAccount extends Account{
4. private String sid;
270
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeAccount.java
1. package com.durgasoft.pojo;
2.
3. public class EmployeeAccount extends Account{
4. private String eid;
5. private float esal;
6. private String eaddr;
7.
8. public String getEid() {
9. return eid;
10. }
11. public void setEid(String eid) {
12. this.eid = eid;
13. }
14. public float getEsal() {
15. return esal;
16. }
271
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Account.hbm.xml
hibernate.cfg.xml
5. <hibernate-configuration>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.EmployeeAccount;
11. import com.durgasoft.pojo.StudentAccount;
12.
13. public class Test {
14.
15. public static void main(String[] args)throws Exception {
16. Configuration cfg = new Configuration();
17. cfg.configure();
18. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
19. builder = builder.applySettings(cfg.getProperties());
20. StandardServiceRegistry registry = builder.build();
21. SessionFactory factory = cfg.buildSessionFactory(registry);
22. Session session = factory.openSession();
23.
24. StudentAccount sa = new StudentAccount();
25. sa.setAccNo("a1");
273
26. sa.setAccName("AAA");
27. sa.setAccType("Savings");
28. sa.setSid("S1");
Page
29. sa.setSbranch("CS");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
To represent Table Per Class Inheritance Mapping javax.persistence package has provided the
following three Annotations.
1) @Inheritance
2) @DiscriminatorColumn
3) @DiscriminatorValue
1) @Inheritance
EX: @INheritance(strategy=InheritanceType.SINGLE_TABLE)
2) @DiscriminatorColumn
This annotation is able to represent Discriminator Column.
@DiscriminatorColumn(name ="--")
Where "name" is able to take discriminator column name.
274
EX: @DiscriminatorColumn(name="TYPE")
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
It able to provide value to the discriminator column, it must be specified at sub class
Example:
Account.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.DiscriminatorColumn;
5. import javax.persistence.Entity;
6. import javax.persistence.Id;
7. import javax.persistence.Inheritance;
8. import javax.persistence.InheritanceType;
9. import javax.persistence.Table;
10.
11. @Entity
12. @Table(name="account")
13. @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
14. @DiscriminatorColumn(name="TYPE")
15. public class Account {
16. @Id
17. @Column(name="ACCNO")
18. private String accNo;
19. @Column(name="ACCNAME")
20. private String accName;
21. @Column(name="ACCTYPE")
22. private String accType;
23.
24. public String getAccNo() {
25. return accNo;
26. }
27. public void setAccNo(String accNo) {
28. this.accNo = accNo;
29. }
30. public String getAccName() {
31. return accName;
275
32. }
33. public void setAccName(String accName) {
34. this.accName = accName;
Page
35. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
StudentAccount.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.DiscriminatorValue;
5. import javax.persistence.Entity;
6.
7. @Entity
8. @DiscriminatorValue("std")
9. public class StudentAccount extends Account{
10. @Column(name="SID")
11. private String sid;
12. @Column(name="SBRANCH")
13. private String sbranch;
14. @Column(name="SMARKS")
15. private int smarks;
16.
17. public String getSid() {
18. return sid;
19. }
20. public void setSid(String sid) {
21. this.sid = sid;
22. }
23. public String getSbranch() {
24. return sbranch;
25. }
26. public void setSbranch(String sbranch) {
27. this.sbranch = sbranch;
276
28. }
29. public int getSmarks() {
30. return smarks;
Page
31. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EmployeeAccount.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.DiscriminatorValue;
5. import javax.persistence.Entity;
6.
7. @Entity
8. @DiscriminatorValue("emp")
9. public class EmployeeAccount extends Account{
10. @Column(name="EID")
11. private String eid;
12. @Column(name="ESAL")
13. private float esal;
14. @Column(name="EADDR")
15. private String eaddr;
16.
17. public String getEid() {
18. return eid;
19. }
20. public void setEid(String eid) {
21. this.eid = eid;
22. }
23. public float getEsal() {
24. return esal;
25. }
26. public void setEsal(float esal) {
27. this.esal = esal;
28. }
29. public String getEaddr() {
30. return eaddr;
277
31. }
32. public void setEaddr(String eaddr) {
33. this.eaddr = eaddr;
Page
34. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.Account;
11. import com.durgasoft.pojo.EmployeeAccount;
12. import com.durgasoft.pojo.StudentAccount;
13.
278
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In case of "Table Per Subclass" inheritance mapping, we have to prepare a seperate table
for each and every class[for both super class and sub classses] existed in inheritance.
While preparing tables for sub classes we have to provide a join column which must be
279
primary key in super class respective table and in sub class respectiove tables.
In hibernate applications, if we store sub class objects in database then Hibernate software
has to recognize and store super class properties data in super class respective table and
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <hibernate-mapping>
2. <class name="--" table="--"
3. ------
4. <joined-subclass name="--" table="--">
5. <key column="--"/>
6. -----
7. </join-subclass>
8. ----
9. </class>
10. </hibernate-mapping>
Where "<joined-subclass>" tag is able to configure sub class, where "name" attribute will
take fully qualified name of the respective sub class and "table" attribute will take sub class
respective table name.
Where "<key>" tag is able to take join key which is available in sub class respective table.
280
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Payment.java
1. package com.durgasoft.pojo;
2.
3. public class Payment {
4. private String tx_Id;
5. private String payment_Date;
6. private long payment_Amt;
7.
8. public String getTx_Id() {
9. return tx_Id;
10. }
11. public void setTx_Id(String tx_Id) {
12. this.tx_Id = tx_Id;
13. }
14. public String getPayment_Date() {
15. return payment_Date;
16. }
17. public void setPayment_Date(String payment_Date) {
18. this.payment_Date = payment_Date;
19. }
20. public long getPayment_Amt() {
21. return payment_Amt;
22. }
23. public void setPayment_Amt(long payment_Amt) {
24. this.payment_Amt = payment_Amt;
25. }
26.
27.
28. }
CardPayment.java
1. package com.durgasoft.pojo;
2.
3. public class CardPayment extends Payment {
4. private int card_No;
281
8. return card_No;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ChequePayment.java
1. package com.durgasoft.pojo;
2.
3. public class ChequePayment extends Payment {
4. private int cheque_No;
5. private String accNo;
6.
7. public int getCheque_No() {
8. return cheque_No;
9. }
10. public void setCheque_No(int cheque_No) {
11. this.cheque_No = cheque_No;
12. }
13. public String getAccNo() {
14. return accNo;
15. }
16. public void setAccNo(String accNo) {
17. this.accNo = accNo;
18. }
19.
20.
21. }
payment.hbm.xml
282
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
15. </hibernate-configuration>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.CardPayment;
11. import com.durgasoft.pojo.ChequePayment;
12.
13. public class Test {
14.
15. public static void main(String[] args)throws Exception {
16. Configuration cfg = new Configuration();
17. cfg.configure();
18. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
19. builder = builder.applySettings(cfg.getProperties());
20. StandardServiceRegistry registry = builder.build();
21. SessionFactory factory = cfg.buildSessionFactory(registry);
22. Session session = factory.openSession();
23.
24. CardPayment card_Payment = new CardPayment();
25. card_Payment.setTx_Id("t111");
26. card_Payment.setPayment_Date("16/3/18");
27. card_Payment.setPayment_Amt(5000);
28. card_Payment.setCard_No(1234);
29. card_Payment.setExpr_Date("12/12/20");
30.
31. ChequePayment cheque_Payment = new ChequePayment();
32. cheque_Payment.setTx_Id("t222");
33. cheque_Payment.setPayment_Date("17/3/18");
34. cheque_Payment.setPayment_Amt(7000);
35. cheque_Payment.setCheque_No(2345);
36. cheque_Payment.setAccNo("a222");
37.
284
41. tx.commit();
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
SQL>
1) @Inheritance
2) @PrimaryKeyJoinColumn
1) @Inheritance
This annotation is able to represent a particular Inheritance mapping mechanism,it will use
285
"strategy" member to take a particular inheritance mapping, where "strategy" attribvute will
take "JOINED" value constant from "InheritanceType" enum.
Page
EX: @Inheritance(strategy=IOnheritanceType.JOINED)
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
This annotation will be used at sub classes inorder to provide Join Key column name. It will
use "name" attribute to provide "join key column".
EX: @PrimaryKeyJoinColumn(name="TX_ID")
Example:
Payment.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Inheritance;
7. import javax.persistence.InheritanceType;
8. import javax.persistence.Table;
9.
10. @Entity
11. @Table(name="payment")
12. @Inheritance(strategy=InheritanceType.JOINED)
13. public class Payment {
14. @Id
15. @Column(name="TX_ID")
16. private String tx_Id;
17. @Column(name="PAY_DATE")
18. private String payment_Date;
19. @Column(name="PAY_AMT")
20. private long payment_Amt;
21.
22. public String getTx_Id() {
23. return tx_Id;
24. }
25. public void setTx_Id(String tx_Id) {
26. this.tx_Id = tx_Id;
27. }
28. public String getPayment_Date() {
286
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CardPayment.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.PrimaryKeyJoinColumn;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="card_payment")
10. @PrimaryKeyJoinColumn(name="TX_ID")
11. public class CardPayment extends Payment {
12. @Column(name="CARD_NO")
13. private int card_No;
14. @Column(name="EXPR_DATE")
15. private String expr_Date;
16.
17. public int getCard_No() {
18. return card_No;
19. }
20. public void setCard_No(int card_No) {
21. this.card_No = card_No;
22. }
23. public String getExpr_Date() {
24. return expr_Date;
25. }
26. public void setExpr_Date(String expr_Date) {
27. this.expr_Date = expr_Date;
28. }
287
29.
30.
31. }
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.PrimaryKeyJoinColumn;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="cheque_payment")
10. @PrimaryKeyJoinColumn(name="TX_ID")
11. public class ChequePayment extends Payment {
12. @Column(name="CHEQUE_NO")
13. private int cheque_No;
14. @Column(name="ACC_NO")
15. private String accNo;
16.
17. public int getCheque_No() {
18. return cheque_No;
19. }
20. public void setCheque_No(int cheque_No) {
21. this.cheque_No = cheque_No;
22. }
23. public String getAccNo() {
24. return accNo;
25. }
26. public void setAccNo(String accNo) {
27. this.accNo = accNo;
28. }
29.
30.
31. }
hibernate.cfg.xml
4. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5. <hibernate-configuration>
6. <session-factory>
Page
7. <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.CardPayment;
11. import com.durgasoft.pojo.ChequePayment;
12. import com.durgasoft.pojo.Payment;
13.
14. public class Test {
15.
16. public static void main(String[] args)throws Exception {
17. Configuration cfg = new Configuration();
18. cfg.configure();
19. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
20. builder = builder.applySettings(cfg.getProperties());
21. StandardServiceRegistry registry = builder.build();
22. SessionFactory factory = cfg.buildSessionFactory(registry);
23. Session session = factory.openSession();
24.
25. CardPayment card_Payment = (CardPayment)session.get(Payment.class, "t111");
289
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In "Table per Concreate Class" inheritance mapping , we will prepare a seperate table for
each and every sub class containing the columns representing both the super class
properties and the respective sub class properties.
In the above context, if we save any sub class object then Hibernate software has to
distribute sub class objects data in the respective table and in the respective columns. To
achieve this we have to use the following xml tags in hibernate mapping file.
1. <hibernate-mapping>
2. ------
3. <class name="--">
4. ------
5. <union-subclass name="--" table="--">
6. <property name="--" column="--"/>
7. ------
8. </union-subclass>
9. ------
10. </class>
290
11. </hibernate-mapping>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Person.java
1. package com.durgasoft.pojo;
2.
3. public class Person {
4. private String pname;
5. private String paddr;
6.
7. public String getPname() {
8. return pname;
9. }
10. public void setPname(String pname) {
11. this.pname = pname;
12. }
13. public String getPaddr() {
14. return paddr;
15. }
291
18. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. public class Employee extends Person {
4. private String eid;
5. private float esal;
6.
7. public String getEid() {
8. return eid;
9. }
10. public void setEid(String eid) {
11. this.eid = eid;
12. }
13. public float getEsal() {
14. return esal;
15. }
16. public void setEsal(float esal) {
17. this.esal = esal;
18. }
19.
20.
21. }
Customer.java
1. package com.durgasoft.pojo;
2.
3. public class Customer extends Person {
4. private String cid;
5. private String cmobile;
6.
7. public String getCid() {
8. return cid;
9. }
292
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Person.hbm.xml
hibernate.cfg.xml
8. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
9. <property name="connection.user">system</property>
10. <property name="connection.password">durga</property>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10.
11. import com.durgasoft.pojo.Customer;
12. import com.durgasoft.pojo.Employee;
13.
14. public class Test {
15.
16. public static void main(String[] args)throws Exception {
17. Configuration cfg = new Configuration();
18. cfg.configure();
19. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
20. builder = builder.applySettings(cfg.getProperties());
21. StandardServiceRegistry registry = builder.build();
22. SessionFactory factory = cfg.buildSessionFactory(registry);
23. Session session = factory.openSession();
24.
25. Employee emp = new Employee();
26. emp.setPname("AAA");
27. emp.setPaddr("Hyd");
28. emp.setEid("E-111");
29. emp.setEsal(5000);
30.
294
34. cust.setCid("C-111");
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Database:
SQL> create table employee (PNAME varchar2(10) primary key, PADDR varchar2(10), EID
varchar2(5), ESAL float);
SQL> commit;
SQL> create table customer(PNAME varchar2(10) primary key, PADDR varchar2(10), CID
varchar2(5), CMOBILE varchar2(20));
SQL> commit;
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
Example:
Person.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
295
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Inheritance;
Page
7. import javax.persistence.InheritanceType;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Table;
6.
7. @Entity
8. @Table(name="employee")
9. public class Employee extends Person {
10. @Column(name="EID")
11. private String eid;
296
12. @Column(name="ESAL")
13. private float esal;
14.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Customer.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Table;
6.
7. @Entity
8. @Table(name="customer")
9. public class Customer extends Person {
10. @Column(name="CID")
11. private String cid;
12. @Column(name="CMOBILE")
13. private String cmobile;
14.
15. public String getCid() {
16. return cid;
17. }
18. public void setCid(String cid) {
19. this.cid = cid;
20. }
21. public String getCmobile() {
22. return cmobile;
297
23. }
24. public void setCmobile(String cmobile) {
25. this.cmobile = cmobile;
Page
26. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9. import com.durgasoft.pojo.Customer;
10. import com.durgasoft.pojo.Employee;
11.
298
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. Association Mapping:
In General, in Enterprise applications we will use both Object Oriented Data Model and
Relational Data Model to represent data. In Enterprise applications we will use Object
Oriented Data Model in Front-End applications toreprepsent data and we will used
Relational data Model in Back-End Applications to represent Data.
In the above context, both the data models are having their own approaches to represent
data, the differences between data models may provide mismatches between data models,
it may reduce data persistency in Enterprise Applications.
299
In the above context, to improve data persistency we must use ORM implementations,
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Object Oriented Data Model, we are able to achieve associations by declaring one or
Collection of reference variables of an entity class in another entity class.
EX:
1. class Account{
2. }
3. class Address{
4. }
5.
6. class Employee{
7. -----
8. Account acc;// one-to-one association
9. -----
10. Collection<Address> addr; //one-to-many
11. -----
12. }
In relational Data Model, we are able to achieve associations in the following three ways.
To resolve the above associations mismatch between both the data models Hibernate has
provided "Association Mappings".
Hibernate has provided the following four types of Associations mappings inorder to resolve
Associations mismatch.
1. One-To-One Association Mapping
2. One-To-Many Association Mapping
3. Many-To-One Association Mapping
4. Many-To-Many Association Mapping
300
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate applications, to achieve One-To-One Associations, we have to use the following tag
in mapping file.
Example:
Employee.java
1. package com.durgasoft.pojo;
2.
3. public class Employee {
4. private String eid;
5. private String ename;
301
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Account.java
1. package com.durgasoft.pojo;
2.
3. public class Account {
4. private String accNo;
302
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
Account.hbm.xml
5. <hibernate-mapping>
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.Account;
11. import com.durgasoft.pojo.Employee;
304
12.
13. public class Test {
14.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate Applications , to represent one-to-one association JPA has provided the following
annotation as part of javax.persistence package.
@OneToOne(cascade=Val)
Where val may be the constants like ALL, DETACH, MERGE, REFREESH, REMOVE, PERSIST
from CascadeType enum.
The above annotation must be provided just before the entity reference variable in container entity
305
or just above of the getXXX() method w.r.t the entity reference variable.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.CascadeType;
4. import javax.persistence.Column;
5. import javax.persistence.Entity;
6. import javax.persistence.Id;
7. import javax.persistence.OneToOne;
8. import javax.persistence.Table;
9.
10. @Entity
11. @Table(name="emp1")
12. public class Employee {
13. @Id
14. @Column(name="EID", length=5)
15. private String eid;
16. @Column(name="ENAME", length=10)
17. private String ename;
18. @Column(name="ESAL", length=6)
19. private float esal;
20. @Column(name="EADDR", length=10)
21. private String eaddr;
22. @OneToOne(cascade=CascadeType.ALL)
23. private Account acc;
24.
25. public Account getAcc() {
26. return acc;
27. }
28. public void setAcc(Account acc) {
29. this.acc = acc;
30. }
31. public String getEid() {
32. return eid;
33. }
34. public void setEid(String eid) {
35. this.eid = eid;
306
36. }
37. public String getEname() {
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Account.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="account")
10. public class Account {
11. @Id
12. @Column(name="ACCNO", length=10)
13. private String accNo;
14. @Column(name="ACCNAME", length=10)
15. private String accName;
16. @Column(name="ACCTYPE", length=10)
17. private String accType;
18.
19. public String getAccNo() {
307
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
308
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
Page
4. import org.hibernate.SessionFactory;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
44. System.out.println("------------------------");
45. System.out.println("Employee Id :"+emp.getEid());
46. System.out.println("Employee Name :"+emp.getEname());
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
2. One-To-Many Association:
It is a relation between entities where one instance of an entity should be mapped with multiple
instances of another entity.
1. <hibernate-mapping>
2. <class name="--" table="--">
3. -----
4. <set name="---" cascade="--">
5. <key column="---"/>
6. <one-to-many class="---"/>
7. </set>
8. ------
9. </class>
10. </hibernate-mapping>
Where <set> tag is able to represent Collection object, that is, many side in one-to-many
and in many-to-many.
310
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Employee.java
1. package com.durgasoft.pojo;
2.
3. public class Employee {
4. private String eid;
5. private String ename;
6. private float esal;
7. private String eaddr;
8.
9. public Employee(String eid, String ename, float esal, String eaddr) {
10. this.eid = eid;
11. this.ename = ename;
12. this.esal = esal;
13. this.eaddr = eaddr;
14. }
311
15.
16. public String getEid() {
17. return eid;
Page
18. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Department.java
1. package com.durgasoft.pojo;
2.
3. import java.util.Set;
4.
5. public class Department {
6. private String did;
7. private String dname;
8. private Set<Employee> emps;
9.
10. public String getDid() {
11. return did;
12. }
312
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.hbm.xml
Department.hbm.xml
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import java.util.HashSet;
4. import java.util.Set;
5.
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8. import org.hibernate.Transaction;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11. import org.hibernate.cfg.Configuration;
314
12.
13. import com.durgasoft.pojo.Department;
14. import com.durgasoft.pojo.Employee;
Page
15.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
In Hibernate Applications, to represent One-To-Many association , JPA has provided the following
annotation.
315
@OneToMany(cascade=CascadeType.ALL)
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Employee.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="emp1")
10. public class Employee {
11. @Id
12. @Column(name="EID", length=5)
13. private String eid;
14. @Column(name="ENAME", length=10)
15. private String ename;
16. @Column(name="ESAL", length=5)
17. private float esal;
18. @Column(name="EADDR", length=10)
19. private String eaddr;
20.
21. public Employee(String eid, String ename, float esal, String eaddr) {
22. this.eid = eid;
23. this.ename = ename;
24. this.esal = esal;
25. this.eaddr = eaddr;
26. }
27.
28. public Employee(){
29.
30. }
31.
32. public String getEid() {
33. return eid;
34. }
35. public void setEid(String eid) {
316
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Department.java
1. package com.durgasoft.pojo;
2.
3. import java.util.Set;
4.
5. import javax.persistence.CascadeType;
6. import javax.persistence.Column;
7. import javax.persistence.Entity;
8. import javax.persistence.Id;
9. import javax.persistence.OneToMany;
10. import javax.persistence.Table;
11. @Entity
12. @Table(name="dept")
13. public class Department {
14. @Id
15. @Column(name="DID", length=5)
16. private String did;
17. @Column(name="DNAME", length=10)
317
21.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
16. </session-factory>
17. </hibernate-configuration>
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.test;
2.
3. import java.util.HashSet;
4. import java.util.Set;
5.
6. import org.hibernate.Session;
7. import org.hibernate.SessionFactory;
8. import org.hibernate.Transaction;
9. import org.hibernate.boot.registry.StandardServiceRegistry;
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11. import org.hibernate.cfg.Configuration;
12.
13. import com.durgasoft.pojo.Department;
14. import com.durgasoft.pojo.Employee;
15.
16. public class Test {
17.
18. public static void main(String[] args) throws Exception{
19. Configuration config = new Configuration();
20. config.configure();
21. StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
22. builder = builder.applySettings(config.getProperties());
23. StandardServiceRegistry registry = builder.build();
24. SessionFactory sessionFactory = config.buildSessionFactory(registry);
25. Session session = sessionFactory.openSession();
26. /*
27. Employee e1 = new Employee("E-111", "AAA", 5000, "Hyd");
28. Employee e2 = new Employee("E-222", "BBB", 6000, "Hyd");
29. Employee e3 = new Employee("E-333", "CCC", 7000, "Hyd");
30. Employee e4 = new Employee("E-444", "DDD", 8000, "Hyd");
31.
32. Set<Employee> emps = new HashSet<Employee>();
33. emps.add(e1);
34. emps.add(e2);
35. emps.add(e3);
36. emps.add(e4);
37.
319
41. dept.setEmps(emps);
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
3. Many-To-One Association:
It is a relation between entity classes, where multiple instances of an entity should be mapped
with exactly single instance of another entity.
To provide Many-To-One Association in Hibernate applications then we have to use the following
tag in mapping file.
where "name" attribute will take property name which is representing many to one relation.
where "class" attribute will take contained class name.
320
where "cascade" attribute will take the values like all, insert,.......
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
EX:
Branch.java
1. package com.durgasoft.pojo;
2.
3. public class Branch {
4. private String bid;
5. private String bname;
6.
7. public String getBid() {
8. return bid;
9. }
10. public void setBid(String bid) {
11. this.bid = bid;
12. }
13. public String getBname() {
14. return bname;
15. }
16. public void setBname(String bname) {
321
20. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. package com.durgasoft.pojo;
2.
3. public class Student {
4. private String sid;
5. private String sname;
6. private String saddr;
7. private Branch branch;
8.
9. public String getSid() {
10. return sid;
11. }
12. public void setSid(String sid) {
13. this.sid = sid;
14. }
15. public String getSname() {
16. return sname;
17. }
18. public void setSname(String sname) {
19. this.sname = sname;
20. }
21. public String getSaddr() {
22. return saddr;
23. }
24. public void setSaddr(String saddr) {
25. this.saddr = saddr;
26. }
27. public Branch getBranch() {
28. return branch;
29. }
30. public void setBranch(Branch branch) {
31. this.branch = branch;
32. }
33.
34.
35. }
Branch.hbm.xml
322
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Student.hbm.xml
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.Branch;
11. import com.durgasoft.pojo.Student;
12.
13. public class Test {
14.
323
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
58. }
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Example:
Branch.java
1. package com.durgasoft.pojo;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6. import javax.persistence.Table;
7.
8. @Entity
9. @Table(name="branch")
10. public class Branch {
11. @Id
12. @Column(name="BID", length=5)
13. private String bid;
14. @Column(name="BNAME", length=10)
15. private String bname;
16.
17. public String getBid() {
18. return bid;
19. }
20. public void setBid(String bid) {
21. this.bid = bid;
22. }
23. public String getBname() {
24. return bname;
25. }
26. public void setBname(String bname) {
27. this.bname = bname;
28. }
29.
30.
31. }
325
Student.java
1. package com.durgasoft.pojo;
Page
2.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.cfg.xml
Test.java
1. package com.durgasoft.test;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.Transaction;
6. import org.hibernate.boot.registry.StandardServiceRegistry;
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8. import org.hibernate.cfg.Configuration;
9.
10. import com.durgasoft.pojo.Branch;
11. import com.durgasoft.pojo.Student;
327
12.
13. public class Test {
14.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
4. Many-To-Many Associations:
It is a relation between entities , where multiple instances of an entity must be mapped with
329
To repesent Many-To-Many mapping we have to use the following tags in mapping file.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Where "<set>" tag is representing many side, where "name" attribute in <set> tag will take
property name which is providing many side , where "table" attribute will take join_table
name, where "cascade" will take "all", "insert", "update",.....
Where "<key>" tag is able to take primary key of the container represented table, where
"column" attribute will take that value.
Example:
Course.java
330
1. package com.durgasoft.pojo;
2.
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Student.java
1. package com.durgasoft.pojo;
2.
3. import java.util.Set;
4.
5. public class Student {
6. private String sid;
7. private String sname;
8. private String saddr;
9. private Set<Course> courses;
10.
331
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
Course.hbm.xml
Student.hbm.xml
332
4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
hibernate.hbm.xml
Test.java
1. package com.durgasoft.test;
2.
3. import java.util.HashSet;
333
4. import java.util.Set;
5.
6. import org.hibernate.Session;
Page
7. import org.hibernate.SessionFactory;
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
47. std1.setSname("AAA");
48. std1.setSaddr("Hyd");
49. std1.setCourses(courses);
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
@ManyTomany(cascade=”_”)
@jointable(name=”_”,joincolumns=”_”,inversejoincolumns=”_”)
@joincolumn(name=”_”)
Where, @joincolumn annotation can be used to represent a column available in join table.
335
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
1. <hibernate-configuration>
2. ----
3. <mapping class =”student”/>
4. <mapping class=”course”/>
5. <session-factory>
6. </hibernate-configuration>
Student.java
1. Import java.util.*;
2. Import javx.persistence.*;
3. @entity
4. @table(name=”student”)
5. Public class student
6. {
7. @id
8. @column (name=”sid”);
9. Private string sid;
10. @column(name=”sname”)
11. Private string sname;
12. Private string sname;
13. @Many to Many(cascade=cascadetype.All)
14.
15.
16.
17. @JoinTable(name=”student_course”,joinColumns={@JoinColumn(name=”sid”)},inverseJoi
nColumns={@JoinColumn(name=”cid”)})
18. Private Collection<Course> courses;
19. setXxx(-);
20. getXxx( );
21. }
Course.java
1. Import javax.persistence.*;
2. @Entity
336
3. @Table(name=”course”)
4. Public class Course
5. {
Page
6. @Id
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
ClientApp.java
1. Import java.util.*;
2. Import org.hibernate.*;
3. Import org.hibernate.cfg.*;
4. Public class ClientApp
5. {
6. Public static void main(String
7. {
8. Configuration cfg=new AnnotationConfiguration( );
9. cfg.configure();
10. SessionFactory sf=cfg.buildSessionFactory();
11. Session s=sf.openSession( );
12. Student s1=(Student)s.get(“Student”,”s1”);
13. Sop1(“StudentDetails”);
14. Sopl(“……..”);
15. Sopl (“student id””+s1.getSid());
16. Sopl (“Student name”.”+s1.getSname());
17. Collection c=s1.getCourses();
18. Iterator it=c.iterartor( );
19. Sopl (“course details”);
20. Sopl (“……..”);
21. Sopl (“CID NAME”);
22. Sopl (“……..”);
23. While
24. {
25. Course crs=(Course)it.next( );
26. Sopl (crs.getCid()+” “+crs.getCname());
27. }
28. Sopl (“………”);
29. Student s2=(Student)s.get(“Student”,”s2”);
337
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
338
Page
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com