6. Hibernate - Javasiva

flutheronioneyedΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 10 μήνες)

109 εμφανίσεις

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
7

of
34

6.

Hibernate


The J2EE field is a good wit
h excitement about a very popular open
-
source technology.Feedback
from J2EE programmers in industry says that knowledge of Hibernate is mandatory for all J2EE
professionals.

There have been a number of ORM technologies,in recent past.. TopLink is one such
tool ,
subsequently adopted by Oracle and so proprietary. Hibernate from SourceForge and OJB(Object
-
Relational
-
Bridge),iBatis from Apache are well known ORM tools, open
-
source and free. JDO from
sun, also falls within the same category.

Hibernate is an ope
n source object/relational mapping tool for Java and developed in
SourceForge.net. .Hibernate not only takes care of the mapping from Java classes to database
tables , but also provides data query and retrieval facilities and can significantly reduce
devel
opment time.Hibernates goal is to relieve the developer from 95 percent of common data
persistence related programming tasks.

Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in
both open source and commer
cial projects

Hibernate is very flexible O/R mapping tool. It works with many databases and it's very easy to
move the application from one database to another database
.

6.1.

Hibernate Architecture


The
below

diagram shows that Hibernate is using the database
and configuration data to
provide persistence services to the application.


According the Artchitecture we can understands the below points

1)

Hibernate itself opens connection to database,

2)

converts HQL (Hibernate Query Language) statements to database spe
cific statement,

3)

receives result set,

4)

then performs mapping of these database specific data to Java objects which are
directly used by Java application.



5)

Hibernate uses the database specification from Hibernate XML/Properties file.
Automatic mapping
is performed on the basis of the properties defined in hbm XML
file defined for particular Java object.

6)

To use Hibernate, it is required to create Java classes that represents the table in the
database and then map the instance variable in the class with t
he columns in the
database. Then Hibernate can be used to perform operations on the database like
select, insert, update and delete the records in the table. Hibernate automatically
creates the query to perform these operations.


Hibernate
will work with t
hree main components:


Connection Management
:
Hibernate Connection management service provide
efficient management of the database connections. Database connection is the most
Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
8

of
34

expensive part of interacting with the database as it requires a lot of resources
of
open and close the database connection.


Transaction management
:Transaction management service provide the ability to
the user to execute more than one database statements at a time.


Object relational mapping
:Object relational mapping is technique of

mapping the
data representation from an object model to a relational data model. This part of the
hibernate is used to select, insert, update and delete the records form the
underlying table.

6.2.

Configuring Hibernate


Hibernate uses the hibernate.cfg.xml to

create the connection pool and setup required
environment.
Here is the example formate of
hibernate.cfg.xml

to work with
Oracle

Database
.

<?xml version='1.0' encoding='utf
-
8'?>

<!DOCTYPE hibernate
-
configuration PUBLIC

"
-
//Hibernate/Hibernate Configuration
DTD//EN"

"http://hibernate.sourceforge.net/hibernate
-
configuration
-
3.0.dtd">


<hibernate
-
configuration>


<session
-
factory>


<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<property name="hibernate.connection.u
rl">jdbc:oracle:thin:@localhost:1521:orcl</property>


<property name="hibernate.connection.username">scott</property>


<property name="hibernate.connection.password">tiger</property>


<property name="dialect">org.hibernate.dialect.Ora
cleDialect</property>


<property name="hibernate.hbm2ddl.auto">update</property>



<!
--

Location of Mapping files
--
>


<mapp
ing resource=”
customer.hbm.xml"/>


</session
-
factory>

</hibernate
-
configuration>


To use Hibernate
-
provided JDBC connections, the configuration file requires the following
five properties:



connection.driver_class
-
The JDBC connection class for the specific database


connection.url
-
The full JDBC URL to the database


connection.username
-
The username used to connect to the database


connection.password
-
The password used to authenticate the username


dialect
-
The na
me of the SQL dialect for the database


The dialect property
is
to

tells the Hibernate that
what kind of

Database

we are using
.
Hibernate supports many database.we can use the following databases dialect type
property:


a.

DB2
-

org.hibernate.dialect.DB2Dialect

b.

HypersonicSQL
-

org.hibernate.dialect.HSQLDialect

c.

In
formix
-

org.hibernate.dialect.InformixDialect

d.

Ingres
-

org.hibernate.dialect.IngresDialect

e.

Interbase
-

org.hibernate.dialect.InterbaseDialect

f.

Pointbase
-

org.hibernate.dialect.PointbaseDialect

g.

PostgreSQL
-

org.hibernate.dialect.PostgreSQLDiale
ct

h.

Microsoft SQL Server
-

org.hibernate.dialect.SQLServerDialect

i.

MySQL
-

org.hibernate.dialect.MySQLDialect

j.

Oracle (any version)
-

org.hibernate.dialect.OracleDialect

k.

Oracle 9
-

org.hibernate.dialect.Oracle9Dialect

l.

SAP DB
-

org.hibernate.dia
lect.SAPDBDialect

m.

Sybase
-

org.hibernate.dialect.SybaseDialect

n.

Sybase Anywhere
-

org.hibernate.dialect.SybaseAnywhereDialect


Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
9

of
34


hbm2ddl
.auto
-
to create/update the table structure at run time. Here is the
property defined into hibernate.cfg.xml file:

<property
name="hibernate.hbm2ddl.
auto">update</property>

The above
pro
perty

is good and can be used at development time, in production
application you must set the value to none. Use this utility carefully otherwise it will drop
your existing tables along with the data.


Note:
The hbm2ddl.auto option turns on automatic generation of database schemas
directly into the database.


The
<mapping resource="c
ustomer
.hbm.xml"/>

pro
perty is the mapping for our
customer

table.


Note:
It is
your choice to use
either hibernate.properties or hiberna
te.cfg.xml, both are
equivalent.


Example:

Here is the example formate of
hibernate.cfg.xml

to work with
DB2

Database
.

<?xml version='1.0' encoding='utf
-
8'?>

<!DOCTYPE hibernate
-
configuration PUBLIC

"
-
//Hibernate/Hiber
nate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate
-
configuration
-
3.0.dtd">


<hibernate
-
configuration>


<session
-
factory>


<property
name="hibernate.connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>


<proper
ty name="hibernate.connection.url">


jdbc:db2://179
.1
5.6
.1
20
:50003/mcadb


</property>


<property name="hibernate.connection.username">
javasiva
</property>


<property name="hibernate.connection.password">
javasiva
</property>



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


<property name="dialect">org.hibernate.dialect.DB2Dialect</property>


<property name="hibernate.hbm2ddl.auto">update</property>


<!
--

Mapping files
--
>


<mapping resource=”custome
r.hbm.xml"/>


</session
-
factory>

</hibernate
-
configuration>



Jars required to work with hibernate

The following are the jar to be placed in the
classe path





The
hibernate3.jar

contains all the core
hibernate files.






Note
:
The ojdbc14
.jar

is used, to connect with the
Oracle database, if you are using someother database
then you need to include that jar file instead of this.



All the above

jars can be download
from www.javasiva.in
.


Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
10

of
34

6.3.

How To

Work
With Hibernate


To work with hibernate we need to create a Simple POJO and mapping file as decribed in
below sections.

6.3.1.

Writing Persistence Class


Hibernate uses the Plain Old Java Objects (POJOs) cla
sses to map to the database
table. We can configure the variables to map to the database column. Here is the
code for

Customer Class.

package com.jsf.examples;

public class Customer {


private String uname;


private String pass;


private String
email;



public String getUname() {


return uname;


}


public void setUname(String uname) {


this.uname = uname;


}


public String getPass() {


return pass;


}


public void setPass(String pass) {


this.pass =

pass;


}


public String getEmail() {


return email;


}


public void setEmail(String email) {


this.email = email;


}



}


6.3.2.

Mapping Through
h
bm.xml file


Object/relational mappings are usually defined in an XML document. The
mapping
document is designed to be

readable and hand
-
editable. The mapping language is
Java
-
centric, meaning that mappings are constructed

around persistent class
declarations, not table declarations.

We will create
customer.hbm.xml

to map
above
Customer

O
bject to the
CUSTOMER

table in the database. Here is the content of customer.hbm.xml

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

<!DOCTYPE hibernate
-
mapping PUBLIC "
-
//Hibernate/Hibernate Mapping DTD
3.0//EN" "http://hibernate.sourceforge.net/hibernate
-
mapping
-
3.0.dtd">

<hibernate
-
mapping>


<class name="com.jsf.examples.Customer" table="
CUSTOMER
">


<id column="CUSTNAME" name="uname" type="string">


<generator class="assigned"/>


</id>


<property column="CUSTPWD" name="pass"/>


<property column=
"CUSTEMAIL" name="email"/>


</class>

</hibernate
-
mapping>


Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
11

of
34

We can observe that fields of Customer Class(uname,pass,email) are mapped to
CUSTOMER table(CUSTNAME,CUSTPWD,CUSTEMAIL).

Now let's understand the each component of the mapping file. Here are impo
rtant
elements of the mapping file:



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



<class>
:

element maps the class object with
corresponding entity in the
database. It also tells what table in the database has to access and what column
in that table it should use. Within one <hibernate
-
mapping> element, several
<class> mappings are possible.



<id>
:

unique identifier to identify an
d object. In fact <id> element map with the
primary key of the tab
le. In our code :<id column
="
CUSTNAME
" type="
string
"
name
="
uname”
>

which is a
primary key maps to the
CUSTNAME
field of the
table
CUSTOMER
. The attributes of the id element are:


a.

name: The
property name used by the persistent class.

b.

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

c.

type: The Java data type used.





<generator>
:
is used to generate the primary key for the new record. Here is
some of the commonly used generators :


a.

In
crement
-

This is used to generate primary keys of type long, short or
int that are unique only. It should not be used in the clustered
deployment environment.

b.

Sequence
-

Hibernate can also use the sequences to generate the
primary key. It can be used with

DB2, PostgreSQL, Oracle, SAP DB
databases.

c.

Assigned
-

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






<property>
:

define standard Java attributes and their mapping into database
schema. The property element supports the column

child element to specify
additional properties, such as the index name on a column or a specific column
type.


6.3.3.

Accessing Hibernate


a.

First we need to get the instance of SessionFactory by specifying the location of
hibernate configuration file
.

b.

get instan
ce of Session

c.

Once we got the Session object, we can do any of the task by getting
Transaction object.


The above three statements can be coded like below.



SessionFactory

sessfact = new
Configuration().configure("/com/javasiva/hiber/example/hibernate.cfg
.xml").buildSes
sionFactory();

Session
session = sessfact.openSession();


Transaction tx = session.beginTransaction();//transactin begining



uname = scan.next();


pass = scan.next();


email = scan.next
();


Customer
cfm = new Customer();


cfm.setUname(uname);

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
12

of
34


cfm.setPass(pass);


cfm.setEmail(email);

//the below save() method will persist the customer object to database table.



session.save(cfm);


tx.commit();//transaction ending


Now you can find a row with the above values in the database table.


6.4.

JDBC vs Hibernate


How

Hibernate
is
better than JDBC
is described in below points



a.

Relational Persistence for JAVA:
Wor
king with both Object
-
Oriented software and
Relational Database is complicated task with JDBC because there is mismatch
between how data is represented in objects versus relational database. So with JDBC,
developer has to write code to map an object model'
s data representation to a
relational data model and its corresponding database schema. Hibernate is flexible
and powerful ORM solution to map Java classes to database tables. Hibernate itself
takes care of this mapping using XML files so developer does no
t need to write code
for this.

b.

Transparent Persistence:
The automatic mapping of Java objects with database tables
and vice versa is called Transparent Persistence. Hibernate provides transparent
persistence and developer does not need to write code expli
citly to map database
tables tuples to application objects during interaction with RDBMS. With JDBC this
conversion is to be taken care of by the developer manually with lines of code.

c.

Support for Query Language:
JDBC supports only native Structured Query

Language
(SQL). Developer has to find out the efficient way to access database, i.e to select
effective query from a number of queries to perform same task. Hibernate provides a
powerful query language Hibernate Query Language (independent from type of
d
atabase) that is expressed in a familiar SQL like syntax and includes full support for
polymorphic queries. Hibernate also supports native SQL statements. It also selects
an effective way to perform a database manipulation task for an application.

d.

Databas
e Dependent Code:
Application using JDBC to handle persistent data
(database tables) having database specific code in large amount. The code written to
map table data to application objects and vice versa is actually to map table fields to
object propertie
s. As table changed or database changed then it’s essential to change
object structure as well as to change code written to map table
-
to
-
object/object
-
to
-
table. Hibernate provides this mapping itself. The actual mapping between tables and
application objec
ts is done in XML files. If there is change in Database or in any table
then the only need to change XML file properties.

e.

Maintenance Cost
:
With JDBC, it is developer’s responsibility to handle JDBC result set
and convert it to Java objects through code
to use this persistent data in application.
So with JDBC, mapping between Java objects and database tables is done manually.
Hibernate reduces lines of code by maintaining object
-
table mapping itself and
returns result to application in form of Java object
s. It relieves programmer from
manual handling of persistent data, hence reducing the development time and
maintenance cost.

f.

Opt
imize Performance:
Caching is retention of data, usually in application to reduce
disk access. Hibernate, with Transparent Pe
rsistence, cache is set to application work
space. Relational tuples are moved to this cache as a result of query. It improves
performance if client application reads same data many

times

g.

Open
-
Source, Zero
-
Cost Product License: Hibernate is an open source
and free to use
for both development and production deployments.

h.

Enterprise
-
Class Reliability and Scalability: Hibernate scales well in any environment,
no matter if use it in
-
house Intranet that serves hundreds of users or for mission
-
critical applicatio
ns that serve hundreds of thousands. JDBC can not be scaled easily.


Working with JDBC

1.

Load the RDBMS specific JDBC driver because this driver actually communicates
with the database.

2.

Open the connection to database
.


3.

Create JDBC Statement object. This ob
ject contains SQL query.

4.

Execute statement which returns result
set(s). ResultSet contains the rows

of
database table
.


Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
13

of
34

5.

Process the result set.

6.

Close the connection.


Example:

Retrieve list of employees from Emp table using JDBC.

List<EmployeeBean> empl
oyeeList = new ArrayList<EmployeeBean>();


/* load the jdbc
-
odbc driver */


class.forName(“
oracle.jdbc.driver.OracleDriver
”);




/* Open a connection to database */


Connection

con =
DriverManager.getConnection(

jdbc:oracle:thin
:@localhost:1521:orcl
”,”scott”,”tiger”
);



/* create Statement object */


Statement stmt = con.createStatement();



/* execute statement */


ResultSet rs = s
tmt.executeQuery("SELECT * FROM emp
");


while ( rs.next() )



{



EmployeeBean eb = new Employeebean();


eb.setNo(rs.get
Int
(“empno”));



eb.setName(rs.getString("
e
name"));


eb.setSalary(rs.getFloat("sal"));



employeeList.add(eb);


}


Working With Hibernate


1.

Load the Hibernat
e configuration file and create configuration object. It will

automatically load all hbm mapping files.

2.

Create session factory from configuration object

3.

Get one session from this session factory.

4.

Create HQL query.

5.

Execute query to get list containing J
ava objects.


Example
: Retrieve list of employees from Emp table using Hibernate.

/* Load the hibernate configuration file */


Configuration config = new Configuration();


config.configure("/com/javasiva/hiber/example/hibernate.cfg.xml");


/* Create

the session factory */


SessionFactory sessionFactory = cfg.buildSessionFactory();


/* Retrieve the session */


Session session = sessionFactory.openSession();


/* create query */


Query query = session.createQuery("from EmployeeBean”);





/* execute query and get result in form of Java objects */


List<EmployeeBean> finalList = query.list();


EmployeeBean.hbm.xml File

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

<!DOCTYPE hibernate
-
mapping PUBLIC


"
-
//Hibernate/Hibernate Mapping DTD 3.0
//EN"


"http://hibernate.sourceforge.net/hibernate
-
mapping
-
3.0.dtd">

<hibernate
-
mapping>


<class name="com.mf.bean.EmployeeBean"


table="emp">


<id name="no" type="int” column=”empno” >


<generator class="assigned"/>


</id>




<property name="name">


<column name="
e
name" />


</property>




<property name="salary">


<column name="sal" />

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
14

of
34


</property>


</class>

</hibernate
-
mapping>


6.5.

HQL


Hibernate Query Language is much like SQL and are cas
e
-
insensitive, except for the
names of the Java Classes and properties. Hibernate Query Language is used to execute
queries against database. Hibernate automatically generates the sql query and execute it
against underlying database.
Hibernate Query Languag
e uses Classes and properties
instead of tables and columns.

Hibernate Query Language is extremely powerful and it
supports Polymor
phism and

Associat
ions
.

Advantages of HQL


Full support for relational operations: HQL allows representing SQL queries in the

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



Return result as Object: The HQL queries return the query result(s) in the form of
object(s), which is easy to use. This elemenates the need of creating
the object
and populate the data from result set.





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





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

with dynamic profiling, Inner/outer/full joins, Cartesian
products. It also supports Projection, Aggregation (max, avg) and grouping,
Ordering, Sub queries and SQL function calls.




Database independent: Queries written in HQL are database independent (I
f
database supports the underlying feature).


6.6.

CRUD Operations


Making use of HQL, Here I am explaining the basic operations on any database like
Create,
Retrieve,Update and Deletion operations

using a simple application which you can
find after the followi
ng four sections.First I would like walk you through the basic
operations

like below.

6.6.1.

Create


The createCustomer() receives
a new
Customer

object and h
anded it over to
Hibernate. At this

point, Hibernate takes care of the SQL and executes an
INSERT

on
the
database

using save() method
.

public void createCustomer(Customer cfm) {


session = sessfact.openSession();


Transaction tx = session.beginTransaction();


session.save(cfm);


tx.commit();


}


6.6.2.

Retrieve


Loading One Object

The
loadCustomer() will take primary key and haded it over to hibernate to load
required row as Customer object using load() and returns Customer object.

At
this

point, Hibernate takes care of the SQL and executes an
SELECT

on the database

using load() method
.

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
15

of
34

public Customer loadCustomer(String cname) {


session = sessfact.openSession();


Transaction tx = session.beginTransaction();


Customer cform = (Customer) session.load(Customer.class, cname);


tx.commit();


return cform;


}


If we call the above method then we will recive one customer object and we can see
that object like below.


Customer
cfm =
loadCustomer(uname);
//uname refers customer name


System.out.println("
\
n" + cfm.getPass() + "
\
t" + cfm.getEmail());


Loading
Multiple Objects


The loadCustomers() will prepare rows of CUSTOMER table as that many no of of
Customer objects using list() and returns as a List.

At
this

point, Hibernate takes care
of the SQL and executes an
SELECT

on the database

using list() method
.


public List loadCustomers()


{


session = sessfact.openSession();


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


List list = crit.list();


return list;


}


If we call the above method then we w
ill recive list and traverse all objects like
below.


List l = loadCustomers();


for (int i = 0; i < l.size(); i++) {


cfm = (Customer) l.get(i);


System.out.println(cfm.getUname() + "
\
t" + cfm.getEm
ail());


}


6.6.3.

Update


The updateCustomer() will take modified customer object and
At
this

point, Hibernate
takes care of the SQL and executes an
UPDATE

on the database

using update()
method
.

public void updateCustomer(Customer cform) {



session = sessfact.openSession();


Transaction tx = session.beginTransaction();


session.update(cform);


tx.commit();


}



For this operation, first we need to get persisted object in our hand and modify its
state(changing prop
erties values) and synchronize its state with database table

like
below



Customer cfm =loadCustomer(uname);
//uname refers customer name


cfm.setPass(pass);


cfm.setEmail(email);


u
pdateCustomer(cfm);



6.6.4.

Delete


Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
16

of
34

The delCustomer
() will take customer object and

handed over it to Hibernate.

At
this

point, Hibernate takes care of the SQL and executes an
DELET
E

on the database

using
delete
() method
.

public void delCustomer(Customer cfm) {


session = sessfact.openSession();


Transaction tx = session.beginTransaction();


session.delete(cfm);


tx.commit();


}


For this operation, first we need to get persisted object in our hand and remove it
from the table by se
nding that object to delCustomer() like below.


Customer cfm = lm.loadCustomer(uname);//uname is customer name


delCustomer(cfm);


6.6.5.

Application using the above basic operations


hibernate.cfg.xml

:
It contains configuration details

<?xml version='1.0' encod
ing='utf
-
8'?>

<!DOCTYPE hibernate
-
configuration PUBLIC

"
-
//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate
-
configuration
-
3.0.dtd">

<hibernate
-
configuration>


<session
-
factory>


<property
name="hibernate.conn
ection.driver_class">oracle.jdbc.driver.OracleDriver</property>


<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>


<property name="hibernate.connection.username">scott</property>


<property nam
e="hibernate.connection.password">tiger</property>


<property name="dialect">org.hibernate.dialect.OracleDialect</property>


<property name="hibernate.hbm2ddl.auto">update</property>


<!
--

Location of Mapping files
--
>


<mappin
g resource="com/javasiva/hiber/example/customer.hbm.xml"/>


</session
-
factory>

</hibernate
-
configuration>



customer.hbm.xml

:
It contains mapping details.

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

<!DOCTYPE hibernate
-
mapping PUBLIC "
-
//Hibernate/Hibe
rnate Mapping DTD
3.0//EN" "http://hibernate.sourceforge.net/hibernate
-
mapping
-
3.0.dtd">

<hibernate
-
mapping>


<class name="com.javasiva.hiber.example.Customer" table="CUSTOMER">


<id column="CUSTNAME" name="uname" type="string" unsaved
-
value="true">



<generator class="assigned"/>


</id>


<property column="CUSTPWD" name="pass"/>


<property column="CUSTEMAIL" name="email"/>


</class>

</hibernate
-
mapping>


Model.java

:
Which contains all basic
hibernate related
methods to be called from
cli
ent program


package com.javasiva.hiber.example;

import java.util.List;

import org.hibernate.Criteria;

import org.hibernate.Query;

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
17

of
34

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg
.Configuration;

/**


*


* @author Sivaramayya


*/

public class Model {


public static SessionFactory sessfact;


private Session session = null;


static {


Configuration config = new Configuration();


config.configure("/com/javasiva/h
iber/example/hibernate.cfg.xml");


sessfact = config.buildSessionFactory();


}


public void createCustomer(Customer cfm) {


session = sessfact.openSession();


Transaction tx = session.beginTransaction();


session.save(cfm)
;


tx.commit();


}


public void delCustomer(Customer cfm) {


session = sessfact.openSession();


Transaction tx = session.beginTransaction();


session.delete(cfm);


tx.commit();


}


public void updateCustomer(C
ustomer cform) {


session = sessfact.openSession();


Transaction tx = session.beginTransaction();


session.update(cform);


tx.commit();


}


public Customer loadCustomer(String cname) {


session = sessfact.openSessio
n();


Transaction tx = session.beginTransaction();


Customer cform = (Customer) session.load(Customer.class, cname);


tx.commit();


return cform;


}


public List loadCustomers()


{


session = sessfact.openSes
sion();


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


List list = crit.list();


return list;


}

}


Crud.java

:
Which is client application will call all methods of Model Class


package com.javasiva.hiber.exam
ple;

import java.util.List;

import java.util.Scanner;

/**


*


* @author Sivaramayya


*/

public class Crud {


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


String uname;


String pass;


String email;

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
18

of
34


Model lm = ne
w Model();


Customer cfm;


Scanner scan = new Scanner(System.in);


int choose;


char ch;


do {


System.out.println("chooce one of the following options");


System.out.println("1.Create
\
n2.Retrieve
\
n3.
Update
\
n4.Delete
\
n5.Search
\
n");


choose = scan.nextInt();


switch (choose) {


case 1:


System.out.println("Nter Customer name password and email
\
n");


uname = scan.next();



pass = scan.next();


email = scan.next();


cfm = new Customer();


cfm.setUname(uname);


cfm.setPass(pass);


cfm.setEmail(email);


l
m.createCustomer(cfm);


break;


case 2:


System.out.println("Customers List
\
n
\
n
\
n");


System.out.println("CustomerName
\
t CustomerEmail");


List l = lm.loadCustomers(
);


for (int i = 0; i < l.size(); i++) {


cfm = (Customer) l.get(i);


System.out.println(cfm.getUname() + "
\
t" + cfm.getEmail());


}


break;



case 3:


System.out.println("wh
ich customer want to UPDATE
Nter his details");


uname = scan.next();


pass = scan.next();


email = scan.next();


cfm = lm.loa
dCustomer(uname);


cfm.setPass(pass);


cfm.setEmail(email);


lm.updateCustomer(cfm);


break;


case 4:


System.out.println("which customer want to

DELETE n Nter his name");


uname = scan.next();


cfm = lm.loadCustomer(uname);


lm.delCustomer(cfm);


break;


case 5:


System.out.println("which
customer want to SEARCH n Nter his name");


uname = scan.next();


cfm = lm.loadCustomer(uname);


System.out.println("
\
n" + cfm.getPass() + "
\
t" + cfm.getEmail());


break;



default:


System.out.println("invalid option");


break;


}


System.out.println("Do u want to continue(y/n)");


ch = (char) System.in.read();


} while (ch == 'y');


}//m
ain close

} // end class



Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
19

of
34

6.7.

Examples


Example:
Demonstration of Query

and where clause.

package com.javasiva.hiber.example;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import

org.hibernate.cfg.Configuration;

public class DeleteEx {


public static void main(String[] args) {


Session sess = null;


try {


SessionFactory fact = new

Configuration().configure("/com/javasiva/hiber/example/hibernate.cfg.xml").buildSessionF
actor
y();


sess = fact.openSession();


String na="hema";


Query query = sess.createQuery("delete from Customer where uname =:cname");


query.setString("cname", na);


Transaction tx = sess.beginTransaction();


int row = query.executeUpdate();


tx.commit(
);


if (row == 0){


System.out.println("Doesn't deleted any row!");


}


else{


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


}


sess.close();


}


catch(Exception e){


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


}


}

}


Example:
Demonstration of using

fr
om Clause
.

package com.javasiva.hiber.example;

import org.hibernate.*;

import org.hibernate.cfg.*;

import java.util.*;

public class SelectEx {


public static void main(String[] args) {


Session session = null;


try{


SessionFactory sessionFactory = new

Configuration().configure("/com/javasiva/hiber/example/hibernate.cfg.xml").buildSessionF
actory();


session =sessionFactory.openSession();


Query query = session.createQuery("from Customer");


for(Iterator it=query.iterate();it.hasNext();){

Customer cust=(
Customer)it.next();


System.out.println("Customer Name: " + cust.getUname());


System.out.println("Customer Mail: " + cust.getEmail());


}


session.close();

}catch(Exception e){


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

}finally{


}

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
20

of
34



}

}


Example:
Demonstra
tion of using Select clause.


package com.javasiva.hiber.example;

import org.hibernate.*;

import org.hibernate.cfg.*;

import java.util.*;


public class
SelectClauseEx
{


public static void main(String[] args) {


Session session = null;


try{


SessionFac
tory sessionFactory = new

Configuration().configure("/com/javasiva/hiber/example/hibernate.cfg.xml").buildSessionF
actory();


session =sessionFactory.openSession();


Query query = session.createQuery(
select pass,email from Customer where
uname='mahi'”
);


for(Iterator it=query.iterate();it.hasNext();){

Object[] cust=(Object[])it.next();


System.out.println("Customer Name: " + cust[0]);


System.out.println("Customer Mail: " + cust[1]);


}


session.close();

}catch(Exception e){


System.out.println(e.getMess
age());

}finally{


}



}

}


Example:
Demonstration of using Criteria and Restrictions.

package com.javasiva.hiber.example;

import org.hibernate.*;

import org.hibernate.cfg.*;

import java.util.*;

import org.hibernate.criterion.Expression;

/**


*


* @author

siva


*/

public class CriteriaEx {

public static void main(String[] args) {


Session session = null;



try{



SessionFactory sessionFactory = new

Configuration().configure("/com/javasiva/hiber/example/hibernate.cfg.xml").buildSessionF
actory();


session

=sessionFactory.openSession();


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


crit.add(Expression.and(Expression.eq("uname", "sai"),Expression.eq("pass", "sai")));


List l=crit.list();


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

Customer
cust=(Customer)it.next();


System.out.println("Customer Name: " + cust.getUname());


System.out.println("Customer Mail: " + cust.getEmail());

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
21

of
34


}


session.close();

}catch(Exception e){


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

}finally{


}



}

}


Example:
Dem
onstration of using joins.



6.8.

One
-
to
-
One Relationship


In case of one
-
to
-
one relationships, each row in table A linked to only one row in table B.


From the above diagram we can say that every employee will have only one address.So
We can
implement one
-
to
-
one relationship between t
wo entries Employee and
Address.

We are using two tables E
mployee and
E
mp
loyee_A
ddress and java entities Employee and
Employe
eAddress maps respectively and below

is the
Data Model
diagram
.


hibernate.cfg.xml

This file contains
all configuration details for a database.

<?xml version='1.0' encoding='utf
-
8'?>

<!DOCTYPE hibernate
-
configuration PUBLIC

"
-
//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate
-
configuration
-
3.0.dtd">

<hibernate
-
configur
ation>


<session
-
factory>


<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>


<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>


<property name="hi
bernate.connection.username">scott</property>


<property name="hibernate.connection.password">tiger</property>


<property name="dialect">org.hibernate.dialect.OracleDialect</property>


<property name="hibernate.hbm2ddl.auto">update</p
roperty>


<!
--

Location of Mapping files
--
>


<mapping resource="hiber/relations/onetoone/EmpHasAddress.hbm.xml"/>


</session
-
factory>

</hibernate
-
configuration>


Now we need to create persistant classes like below.

EmployeeAddress
.
java

p
ackage hiber.relations.onetoone;

/**


*


* @author siva


*/

public class EmployeeAddress {

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
22

of
34


private int id;


private int empid;


private String address;


private String country;


public int getId() {


return id;


}


public void setId(int id) {


th
is.id = id;


}


public int getEmpid() {


return empid;


}


public void setEmpid(int empid) {


this.empid = empid;


}


public String getAddress() {


return address;


}


public void setAddress(String address) {


this.address = address;


}


publ
ic String getCountry() {


return country;


}


public void setCountry(String country) {


this.country = country;


}

}


Employee.java

package hiber.relations.onetoone;

/**


*


* @author siva


*/

public class Employee {



private int id;


private Strin
g name;


private EmployeeAddress address;


public int getId() {


return id;


}


public void setId(int id) {


this.id = id;


}


public String getName() {


return name;


}


public void setName(String name) {


this.name = name;


}


public Employ
eeAddress getAddress() {


address.setEmpid(getId());


return address;


}


public void setAddress(EmployeeAddress address) {


this.address = address;


}

}


EmpHasAddress.hbm.xml


Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
23

of
34

<?xml version="1.0"?>

<!DOCTYPE hibernate
-
mapping PUBLIC

"
-
//Hibernate/H
ibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate
-
mapping
-
3.0.dtd">

<hibernate
-
mapping>

<class name="hiber.relations.onetoone.Employee" table="employee">

<id name="id" type="int" column="employee_id" >

<generator class="native"/>

</
id>

<property name="name" type="java.lang.String" column="employee_name" not
-
null="true" length="50"/>

<one
-
to
-
one name="address" class="hiber.relations.onetoone.EmployeeAddress"
property
-
ref="empid" cascade="all"/>

</class>


<class name="hiber.relations.o
netoone.EmployeeAddress" table="employee_address">

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

<generator class="native"/>

</id>

<property name="address" type="java.lang.String" column="address" not
-
null="true"
length="255"/>

<property name="country" type="java
.lang.String" column="country" not
-
null="true"
length="100"/>

<property name="empid" type="int" column="emp_id" not
-
null="true" length="100" />

</class>

</hibernate
-
mapping>


The following mapping tag defines the one
-
to
-
one mapping between Employee and
Em
ployeeAddress entities.

<one
-
to
-
one name="address" class="hiber.relations.onetoone.EmployeeAddress"
property
-
ref="empid" cascade="all"/>

Here empid variable is defined in EmployeeAddress entity which is used for defining the
relationships.

The
cascade

opti
on is used to cascade the required operations to the associated entity. If
the cascade option is set to all then all the operations will be cascaded. For instance when
you save a
Employee

object, the associated
Employee
Address object will also be saved
aut
omatically.

To Run this application

, execute the below class.

OneToOneRelation.java

package hiber.relations.onetoone;

/**


*


* @author siva


*/

import java.util.Scanner;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibern
ate.Transaction;

import org.hibernate.cfg.Configuration;

public class OneToOneRelation {


public static void main(String[] args) {


SessionFactory sessFact = null;


Session sess = null;


try {


sessFact = new
Configuratio
n().configure("hiber/relations/onetoone/hibernate.cfg.xml").buildSessionFactor
y();


sess = sessFact.openSession();


Scanner scan=new Scanner(System.in);


Employee emp = new Employee();


emp.setName("javasiva");

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
24

of
34



EmployeeAddress address = new EmployeeAddress();


address.setAddress("Siripuram,VSP");


address.setCountry("India");


emp.setAddress(address);


Transaction tr = sess.beginTransaction();


ses
s.save(emp);


tr.commit();


} catch (Exception he) {


he.printStackTrace();


}


}

}


In the above program
we are creating the objects of Employee and EmployeeAddress
and filling the values. Then we are setting the
Em
ployeeAddress
object into Emp
loyee
object and finally called

the
sess.save(emp)

method. On calling the save() method on
the Session object, hibernate reads the state of the objects and persists the data into
database

and we can observe the last row in belo
w tables.


Employee


Employee_Address



6.9.

One To Many Relation


Consider the following relationship between
Student

and
Phone

entity.


According to the relationship a student can have any number of phone numbers.To create this
relationship
,we
need to hav
e a STUDENT, PHON
E and STUDENT_PHONE table
s
. The ER
diagram

is shown below
.


This scenario will be explained using below artifacts.

hibernate.cfg.xml

This file contains all configuration details for a database.

<?xml version='1.0' encoding='utf
-
8'?>

<!DOC
TYPE hibernate
-
configuration PUBLIC

"
-
//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate
-
configuration
-
3.0.dtd">

<hibernate
-
configuration>


<session
-
factory>


<property
name="hibernate.connection.driver_class
">oracle.jdbc.driver.OracleDriver</property>


<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>


<property name="hibernate.connection.username">scott</property>


<property name="hibernate.connec
tion.password">tiger</property>


<property name="dialect">org.hibernate.dialect.OracleDialect</property>

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
25

of
34


<property name="hibernate.hbm2ddl.auto">update</property>


<!
--

Location of Mapping files
--
>


<mapping resource="hiber/r
elations/onetomany/StduentHasPhoneNumbers.hbm.xml"/>


</session
-
factory>

</hibernate
-
configuration>


StduentHasPhoneNumbers.hbm.xml


:
T
his file will create three table with the described
structure in this file.


<?xml version="1.0"?>

<!DOCTYPE hiberna
te
-
mapping PUBLIC

"
-
//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate
-
mapping
-
3.0.dtd">

<hibernate
-
mapping>


<class name="hiber.relations.onetomany.Student" table="STUDENT">


<id name="studentId" type="long" c
olumn="STUDENT_ID">


<generator class="native" />


</id>


<property name="studentName" type="string" not
-
null="true" length="100"
column="STUDENT_NAME" />


<set name="studentPhoneNumbers" table="STUDENT_PHONE" cascade="all">


<key column="STUDENT_ID" />


<many
-
to
-
many column="PHONE_NUMBER" unique="true"
class="hiber.relations.onetomany.Phone" />


</set>


</class>




<class name="hiber.relations.onetomany.Phone" table="PHONE">


<id
name="phoneNumber" type="string" column="PHONE_NUMBER">


<generator class="assigned" />


</id>


<property name="company" type="string" length="10" column="COMPANY" />


</class>



</hibernate
-
mapping>





Note:
We use many
-
to
-
many element to create the one
-
to
-
many relationship between the Student
and Phone entities. Since a student can have any number of phone numbers we use a collection
to hold the values. In this case we use Set. Many
-
to
-
many element

is usually used to create
many
-
to
-
many relationship, here we place the unique constraint on the PHONE_
NUMBER

column, this makes the relationship one
-
to
-
many.


Now we need to create persistant classes like below.

Phone.java


package hiber.relations.onetoma
ny;

/**


*


* @author siva


*/

public class Phone {


private String company;


private String phoneNumber;


public Phone() {


}

public Phone(String phoneType, String Number) {



company = phoneType;



phoneNumber = Number;


}


public String getCompany(
) {


return company;


}


public void setCompany(String company) {

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
26

of
34


this.company = company;


}

public String getPhoneNumber() {


return phoneNumber;


}


public void setPhoneNumber(String phoneNumber) {


this.phoneNumb
er = phoneNumber;


}

}


Student.java


package hiber.relations.onetomany;

import java.util.HashSet;

import java.util.Set;

/**


*


* @author siva


*/

public class Student {


private long studentId;


private String studentName;


private Set<Phone> studentP
honeNumbers = new HashSet<Phone>(0);


public Student() {


}


public Student(String studentName) {



this.studentName = studentName;


}


public Student(String studentName, Set<Phone> studentPhoneNumbers) {



this.studentName = studentName;



this.studentPho
neNumbers = studentPhoneNumbers;


}


public long getStudentId() {



return this.studentId;


}


public void setStudentId(long studentId) {



this.studentId = studentId;


}


public String getStudentName() {



return this.studentName;


}


public void setStude
ntName(String studentName) {



this.studentName = studentName;


}


public Set<Phone> getStudentPhoneNumbers() {



return this.studentPhoneNumbers;


}


public void setStudentPhoneNumbers(Set<Phone> studentPhoneNumbers) {



this.studentPhoneNumbers = student
PhoneNumbers;


}

}


OneToManyRelation.java

: This class is for test our scenario.

package hiber.relations.onetomany;

import java.util.HashSet;

import java.util.Set;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate
.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

/**


*


* @author siva

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
27

of
34


*/

public class OneToManyRelation {


public static void main(String[] args) {


SessionFactory sessFact = null;


Transaction
transaction = null;


try {


sessFact = new
Configuration().configure("hiber/relations/onetomany/hibernate.cfg.xml").buildSessionFact
ory();


Session session = sessFact.openSession();


transaction = session.beginTransa
ction();


Set<Phone> phoneNumbers = new HashSet<Phone>();


phoneNumbers.add(new Phone("
Airtel
", "9866723206"));


phoneNumbers.add(new Phone("
BSNL
", "9000387222"));


Student student = new Student("Sivaramayya", ph
oneNumbers);


session.save(student);


transaction.commit();


} catch (HibernateException e) {


transaction.rollback();


e.printStackTrace();


}


}

}


From the above program,
hibernate reads the st
ate of the objects and persists the data
into database

and we can observe the data in below tables.


Student


Phone


Student_Phone



6.10.

Many To One Relation


Consider the following relationship between
Book

and
Author

entity.


According to the relations
hip many books

can have
one author
.To create this relationship
,we
need to have a
BOOK and AUTHOR
tables. The ER diagram

is shown below
.


Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
28

of
34

Both the
BOOK

records points to the same
AUTHOR

record, this illustrates the many
-
to
-
one
mapping.
This scenario will
be explained using below artifacts.


hibernate.cfg.xml

This file contains all configuration details for a database.

<?xml version='1.0' encoding='utf
-
8'?>

<!DOCTYPE hibernate
-
configuration PUBLIC

"
-
//Hibernate/Hibernate Configuration DTD//EN"

"http://hiber
nate.sourceforge.net/hibernate
-
configuration
-
3.0.dtd">

<hibernate
-
configuration>


<session
-
factory>


<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>


<property
name="hibernate.connection.url">j
dbc:oracle:thin:@localhost:1521:orcl</property>


<property name="hibernate.connection.username">scott</property>


<property name="hibernate.connection.password">tiger</property>


<property name="dialect">org.hibernate.dialect.OracleDi
alect</property>


<property name="hibernate.hbm2ddl.auto">update</property>


<!
--

Location of Mapping files
--
>


<mapping resource="hiber/relations/onetomany/StduentHasPhoneNumbers.hbm.xml"/>


</session
-
factory>

</hibernate
-
configur
ation>


Now we need to create persistant classes like below.


Author.java

package hiber.relations.manytoone;

/**


*


* @author siva


*/

public class Author {


private long id;


private String name;


public long getId() {


return id;


}


public void setId(long id) {


this.id = id;


}


public String getName() {


return name;


}


public void setName(String name) {


this.name = name;


}

}


Book.java

package hiber.relations.manytoone;

/**


*


* @author s
iva


*/

public class Book {


private long id;


private String title;


private Author writer;


public long getId() {


return id;


}

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
29

of
34


public void setId(long id) {


this.id = id;


}


public String getTitle() {


ret
urn title;


}


public void setTitle(String title) {


this.title = title;


}


public Author getWriter() {


return writer;


}


public void setWriter(Author writer) {


this.writer = writer;


}

}


BooksHasAuthor.hbm.xm
l

This file contains all mapping details between persisting objects and tables.


<?xml version="1.0"?>

<!DOCTYPE hibernate
-
mapping PUBLIC

"
-
//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate
-
mapping
-
3.0.dtd">

<hibernate
-
mapping>



<class name="hiber.relations.manytoone.Book" table="BOOK">


<id name="id" column="id" type="java.lang.Long" >


<generator class="increment"/>


</id>


<property name="title" column="title" type="java.lang.String
"/>


<many
-
to
-
one name="writer" class="hiber.relations.manytoone.Author" cascade="all" not
-
null="true" column="AUTHOR"/>


</class>


<class name="hiber.relations.manytoone.Author" table="AUTHOR">


<id name="id" column="id" type="java.la
ng.Long">


<generator class="increment"/>


</id>


<property name="name" column="name" type="java.lang.String"/>


</class>


</hibernate
-
mapping>


To run the above scenario,execute the below program.

ManyToOneRelation.java

packag
e hiber.relations.manytoone;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

/**


*


* @author siva


*/

public class ManyToOneRelation {

public static void main(St
ring args[]){


Configuration configuration = new Configuration();


SessionFactory sessionFactory =
configuration.configure("hiber/relations/manytoone/hibernate.cfg.xml").buildSessionFactory();


Session session = sessionFactory.openSes
sion();


Transaction transaction = session.beginTransaction();


Author auth = new Author();


auth.setName("M.Sivaramayya");

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
30

of
34


Book book1 = new Book();


book1.setTitle("EasyC&DS");


book1.setWriter(auth);


Boo
k book2 = new Book();


book2.setTitle("EasyJavaWeb");


book2.setWriter(auth);


session.save(book1);


session.save(book2);


transaction.commit();


session.close();


}

}


From the above program,
hibernate reads the

state of the objects and persists the data
into database

and we can observe the data in below tables.


Book


Author


6.11.

Many To Many Relation


Consider the following relationship between
Student

and
Course

entity.

According to the relationship a student
can enroll in any number of courses and the course can
have any number of students. To create this relationship you need to have a STUDENT,
COURSE and STUDENT_COURSE table
s
. The relational model is shown below.


This scenario will be explained using below

artifacts.

hibernate.cfg.xml

This file contains all configuration details for a database.

<?xml version='1.0' encoding='utf
-
8'?>

<!DOCTYPE hibernate
-
configuration PUBLIC

"
-
//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibe
rnate
-
configuration
-
3.0.dtd">

<hibernate
-
configuration>


<session
-
factory>


<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>


<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhos
t:1521:orcl</property>


<property name="hibernate.connection.username">scott</property>

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
31

of
34


<property name="hibernate.connection.password">tiger</property>


<property name="dialect">org.hibernate.dialect.OracleDialect</property>


<property name="hibernate.hbm2ddl.auto">update</property>


<!
--

Location of Mapping files
--
>



<mapping

resource="hiber/relations/manytomany/StudentsCourses.hbm.xml"/>

</session
-
factory>

</hibernate
-
configuration>


StudentsCourses.hbm.xm
l

This file contains mapping details between persisting objects and database tables.


We use many
-
to
-
many element to create the many
-
to
-
many relationship between the
Student and Course entities. Since a student can enroll in any number of course
s we use a
collection to hold the values. In this case we use Set.


<?xml version="1.0"?>

<!DOCTYPE hibernate
-
mapping PUBLIC

"
-
//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate
-
mapping
-
3.0.dtd">

<hibernate
-
mapping>


<class name="hiber.relations.manytomany.Student" table="STUDENT">


<id name="studentId" type="long" column="STUDENT_ID">


<generator class="native" />


</id>


<property name="studentName" type="string" length="100" not
-
null=
"true"
column="STUDENT_NAME" />


<set name="courses" table="STUDENT_COURSE" cascade="all">


<key column="STUDENT_ID" />


<many
-
to
-
many column="COURSE_ID"
class="hiber.relations.manytomany.Course" />


</set>


</class>


<class name="hiber.relations.manytomany.Course" table="COURSE">


<id name="courseId" type="long" column="COURSE_ID">


<generator class="native"/>


</id>


<property name="courseName" type="string" column="COURSE_NAME"/>


</class>


</hibernate
-
mapping>


Now we need to create Persistent classes like below.

Student.java

package hiber.relations.manytomany;

import java.util.HashSet;

import java.util.Set;

public class Student {


private long studentId;


private String stude
ntName;


private Set<Course> courses = new HashSet<Course>();


public Student(String studentName, Set<Course> courses) {



this.studentName = studentName;



this.courses = courses;


}


public long getStudentId() {



return this.studentId;


}


public void s
etStudentId(long studentId) {



this.studentId = studentId;


}


public String getStudentName() {

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
32

of
34



return this.studentName;


}


public void setStudentName(String studentName) {



this.studentName = studentName;


}


public Set<Course> getCourses() {



retur
n this.courses;


}


public void setCourses(Set<Course> courses) {



this.courses = courses;


}

}

Course.java

package hiber.relations.manytomany;

public class Course {


private long courseId;


private String courseName;


public Course() {


}


public Course(
String courseName) {



this.courseName = courseName;


}


public long getCourseId() {



return this.courseId;


}


public void setCourseId(long courseId) {



this.courseId = courseId;


}


public String getCourseName() {



return this.courseName;


}


public v
oid setCourseName(String courseName) {



this.courseName = courseName;


}

}


To run this application we need to call this below program.

ManyToManyRelation.java

package hiber.relations.manytomany;

import java.util.HashSet;

import java.util.Set;

import org.
hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

/**


*


* @author siva


*/

public class ManyToManyRelation {

public static void main(
String[] args) {


Configuration configuration = new Configuration();


SessionFactory sessionFactory =
configuration.configure("hiber/relations/manytomany/hibernate.cfg.xml").buildSessionFact
ory();


Session session = sessionFactory.ope
nSession();



Transaction transaction = null;



try {




transaction = session.beginTransaction();




Set<Course> courses = new HashSet<Course>();




courses.add(new Course("Java"));




courses.add(new Course("J2EE"));




Student student1 = new Student("Pr
asad", courses);

Miracle Educational Society
Easy

Java




Sivaramayya@9000387222/9866723206 www. javasiva.in

Page
3
3

of
34




Student student2 = new Student("Swathi", courses);




session.save(student1);




session.save(student2);




transaction.commit();



} catch (HibernateException e) {




transaction.rollback();




e.printStackTrace();



} finally {




ses
sion.close();



}


}

}


From the above program,hibernate reads the state of the objects and persists the data
into database and we can observe the data in below tables.

Student


Course



Student_Course






Excercises:

1.

Create an application check
whether

the employee is existed in
employees
table
or not.

2.

Implement the same above application using MySQL.

3.

Display the
student

details and his phone numbers
.(Refer: One
-
To
-
Many
Scenario).

4.

Display the student
details

along with his registered courses.(Refer :Many
-
To
-
Many Scenario).