Sunteți pe pagina 1din 176

http://javaeasytoall.

com

Explore practically and apply instantly

Lara Technologies 080-41310124 1


http://javaeasytoall.com

“Learn everything you can, anytime you can, from


anyone you can - there will always come a time when
you will be grateful you did.”

Congratulations ! B. Uday Kumar (6th Batch) and E.Manikanta (3rd Batch).


For your extraordinary effort

I sincerely appreciate the time you spent for preparing hibernate material. I also
want to extend my personal congratulations. . I can see you invested a lot of time on this
by the content you put in it. I really appreciate the effort.

I honestly wish I could say or do more to show my appreciation but I figured this
was the least I could do. I wish him a very bright future. Thanks for your excellent and
tireless work

Be a worthy role model for our Laraoites

ALL THE BEST

By

B.Ramesh

 Hibernate comes under backend framework which is sitting at


Persistant layer.

Lara Technologies 080-41310124 2


http://javaeasytoall.com

 A frame work which is related to persistant, then it is called as


backend framework.
 Hibernate is built on top of Jdbc.
 Hibernate not only takes care of the mappings from java classes to
database tables but also provides data query and retrival facilities and
can significantly reduce development time otherwise spent with
manualdata handling SQL and JDBC.
 Hibernate’s goal is to relieve the developer from 95% of common data
persistencerelated programming tasks.
 Hibernate is used to Persistance the object state in the persistence
media like database.
 In order to store state of an object in the relational database ORM is
better than plain Jdbc.
 Hibernate is a solution for ORM (Object Relational Mapping System).
It refers to the technique of mapping a data from an object model with
a SQL based commands.
 Frame works which are using ORM technique like TopLinks, IBatis,
Hibernate and Ejb EntityBean, in order to store the state of object.
 Ejb EntityBean can not be used in non-ejb applications. The main
limitation of this is performance.
 If we use JDBC then we want to hard code the sql queries inside the
.java file. If we use Hibernate, then we don’t require to hardcode the
SQL queries in our Java program.
 SQL queries will automatically generated by Hibernate depending on
the database. So whenever we are going to change the database then
.java file is not required to modify. Just changing the url anddriver
class in the configuration file is enough. Then hibernate will generate
sql queries automatically based on database.
 If you are using straightaway Jdbc in java program then achieving
Transaction Management and Cache Management are very difficult.
 And also need to write more code and interaction are very difficult.
 Hibernate is having some methods to interact with database (Those
methods can interact with database through Jdbc only) and also very
few method calls we have to keep in your java program.
 So, .java file will be independent of sql queries or database.

Java App Hibernate Jdbc DB

Lara Technologies 080-41310124 3


http://javaeasytoall.com

 Here Java file sending a action to hibernate but not sql queries.
 Based on the action (i.e insert or update or select) hibernate will
generate sql query and sends to the database.
 If you have a requirement of using some data very frequently, instead of
reading from database every time, read once and keep in the cache and
then 2nd time onwards read from the cache, it reduces number of
network calls.
 If you are using Hibernate, you can change the database one to another
at the time of development itself.
 For example at the time of development you used mysql after
production your client/customer wants to change database to Oracle
then no need to do changes in your java code. You need to do changes
in the configuration file and can execute very successfully.
 Hibernate id typically used in Java Swiong applications, Java Servlet
applications, or J2ee applications using session beans.
 Hibernate supports “Transactions” (Transaction means making
multiple units as a single bundle i.e a transaction can contains insert,
update, delete, if any one query fails to execute then remaining also
will not execute).
 We can achieve mapping through Hibernate very easely.
 By Hibernate we can achieve where conditions very simple.
 By Hibernate managing joins is very easy.
 Hibernate is developed in java so, it is platform independent.by this we
can achieve pure object oriented (database interactions also).
 Hibernate can be used for any kind of java application that can be
standalone, web-application, or enterprise application in where the
database interaction is required.
 Hibernate uses Object oriented querying language.
 Hibernate is free to use no need to buy any licences. It is also a
opensource, we can download the source code and can enhance.
 Usage of Hibernate is nothing but using sessipn object effectively.
 Hibernate maintains two level cache.

Lara Technologies 080-41310124 4


http://javaeasytoall.com

 A major portion of the development of an enterprise application


involves the creation and maintenance of the persistence layer used to
store and retrieve objects from the database of choice.
 If changes are made to the underlying database schema, it can be
expensive to propagate those changes to the rest of the application.
 Hibernate steps into fill this gap, providing an easy to use and powerfull
object relational persistence framework for java applications.
 Hibernate provides support for collections and object relations, as well
as composite types. Userdefined data types and composite primary keys
give additional flexibility to support legacy applications.

Hibernate key features:

 Natural programming model: Hibernate supports natural OO idiom,


inheritance, polymorphism, composition and the java collection
framework.
 Support for ultra-fine-grained object models: a rich variety of
mappings for collections and dependent objects.
 No build-time bytecode enhancement: there is no extra code
genaration or bytecode processing steps in your build procedure.
 Extra scalability: Hibernate is extremely performant has dual-layer
cache architecture, and may be used in a cluster.
 The query language: Hibernate addresses both sides of the problem;
not only how to get objects into the database, but also how to get them
out again.
 Support for application transactions: Hibernate supports both long-
lived persistance contexts and detach/research and takes care of
optimistic locking automatically.
 Free/openSource: Hibernate is lisensed under the LGPL (Lesser
GNU Public Lisesce).
 Ejb3.0: Hibernate implements the persistance API and quarey
language defined by EJB3.0 persistence, two members of the
Hibernate team are active in the expert group. It provides three full-
featured query facilities those are ‘Hibernate Query Language’,
‘Hibernate Criteria Query’, ‘dialect of the database’.
 Hibernate is scalable: Hibernate is very performent and due to its
dual-layer architecture can be used in the clustered environment.

Lara Technologies 080-41310124 5


http://javaeasytoall.com

 Less devolopment time: Hibernate reduces the development timings


as it supports inheritance, polymorphism, composition and the java
collection framework.
 Automatic key generation: Hibernate supports the automatic
generation of primary key.
 Enhanced Criteria query API: with full support for
projection/aggregation and subselects.
 EJB3-Stylepersistance operation: defines the create () and merge ()
operations.which are slightly different to Hibernate’s saveOrUpdate ()
and saveOrUpdatecopy () operations. Hibernate3 will support all four
operations as methods of the session interface.
 Hibernate XML binding enables data to be represented as XML and
POJOs interchangeabily.
 The EJB3 draft specification support for POJO persistance and
annotations.
Hibernate Based Application Architecture:

Persistant Objects

Sessoion SessionFactory

Configuration Query

Transaction

JDBC

Lara Technologies 080-41310124 6


http://javaeasytoall.com

To use Hibernate, it is required to create a java class that represents the table
in the database and then map the instance variable in the class with the
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 architecture has three main components:

1. connection Management:
2. transaction Management:
3. object Relational Management:

Hibernate provides a lot of flexibility in use. It is called ‘lite’ architecture


when we only use the object relational mapping component. While in ‘full
cream’ architecture all the three component Objects Relaational Mappings
are used.

Hibernatre is being used with other configuration management and


transaction management tools. For example apache DBCP is used for
connection pooling with the Hibernate.

Pre requisits to use hibernate:

1. Any one of the database.


2. For that database 4th type of driver jar file.
3. Java Development Kit of J2SE.
4. If you are using web-application then only any one of the webServer.

The official website for hibernate is ‘www.hibernate.org’.


In order to interact with database by using Hibernate need to update
classpath or buildpath with relavent jar files.

Updating buildpath:

Inorder to use hibernate framework we should update classpath or


buildpath with the relavent and dependent JAR files those are:
1. hibernate-3.2.jar file
2. Driver JAR file
3. dependent JAR files which are inside lib folder of hibernate-3.jar

Lara Technologies 080-41310124 7


http://javaeasytoall.com

Hibernate API

Session (org.hibernate.Session):
Session object is similar to the HttpSession object.s A single-threaded,
short-lived object representing a conversation between the application and
the persistent store. Wraps a JDBC connection. Factory for Transaction.
Holds a mandatory (first-level)cache of persistent objects, used when
navigating the object graph or looking up objects by identifier.

SessionFactory (org.hibernate.SessionFactory):

SessionFactory is a singletone object for entire application there will be one


sessinfactory object. A single-threaded, short-lived object representing a
conversation between the application and the persistent store. Wraps a JDBC
connection. Factory for Transaction. Holds a mandatory (first-level) cache of
persistent objects, used when navigating the object graph or looking up
objects by identifier.

Configuration (org.hibernate.cfg.Configuration):

In order to complete configuration of the of the hibernate we use this class.

Query(org.hibernate.cfg.query):
In order to construct HQL queries we use this interface. Not only this
interface we can also use Criteria interface.

Transaction (org.hibernate.Transaction):

(Optional) A single-threaded, short-lived object used by the


application to specify atomic units of work. Abstracts application from
underlying JDBC, JTA or CORBA transaction. A Session might span
several Transactions in some cases. However, transaction
demarcation, either using the underlying API or Transaction, is never
optional!

With hibernate API jdbc get the hql queries and it interact with the Jdbc and
it will convert the hql queries in to the sql queries to interact with the
database.

Lara Technologies 080-41310124 8


http://javaeasytoall.com

Getting Start with Hibernate:

 Hibernate is free to use and it is openSource .


 There is a website to download (www.hibernate.org). At the time of
downloading we will get one zip file i.e hibernate-3.2.3.ga.zip.
Unzip it to the favourable location. Inside unzipped folder you can
find many folders. Among them hibernate3.jar (i.e core hibernate)
and jar files in the lib (hibernate dependence .jar files) are required to
develop any hibernate related application.
 Take both jar files and update classpath or buildpath (in eclipse) or
copy into lib folder of web application.

Development steps for Application project:

For Every framework there will be one configuration file Eg: for struts
struts-config.xml. Like wise for hibernate also there is one config file i.e
hibernate.config.xml
 First develop one hibernate.config.xml for your application under
classpath. Inside this xml file we have to explian about.
1. DriverClassName.
2. URL.
3. Username to connect to database;
4. Password to connect to database.
5. Type of 2nd level cache.
6. Dialect class. Through this we are updating database
type (Dialect means pronouncing same language in
different accents).

 Develop “POJO class”(Plain Old Java Object). It is similar to


usebean or form bean.
 For every pojo class develop one hbm (hibernate mapping) file.
 Update configuration file with hbm file path.
 Write client program .Inside this, we have to follow following steps.
1. Open hibernate session.
2. Start transaction.
3. Use transaction
4. Commit transaction
5. Close the session

Lara Technologies 080-41310124 9


http://javaeasytoall.com

Developing core java related project:

Developing a simple helloworld stand alone application by using


mySql database.

1. Go to eclipse and create one core java related project.


2. Now update the buildpath with hibernate3.jar (i.e core hibernate) ,
jar files from lib(hibernate dependence .jar files) and the Driver jar
file.

3. Now develop hibernate.cfg.xml file inside src folder

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
com.mysql.jdbc.Driver</property>
<property name="connection.url">
jdbc:mysql://localhost/lara</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

Lara Technologies 080-41310124 10


http://javaeasytoall.com

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


<property name="hbm2ddl.auto">create</property>

<mapping resource="com/lara/Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

4. Now create a package structure and develop a Pojo object.

We want to crate table for Person with column names as


(Person_ID, PERSON_NAME, PERSON_AGE).So first develop one Pojo
class with all these attributes

package com.lara;
public class Person
{
private Integer id;
private String personName;
private Integer personAge;

public int getId () {


return id;
}
public void setId (int id) {
this.id = id;
}
public String getPersonName () {
return personName;
}

Lara Technologies 080-41310124 11


http://javaeasytoall.com

public void setPersonName (String personName) {


this.personName = personName;
}
public int getPersonAge () {
return personAge;
}
public void setPersonAge (int personAge) {
this.personAge = personAge;
}
}

5. Now develop one hbm file for every Pojo class in one package.

In hibernate with out primary key we can’t develop any table.


In hbm file we want to take care about all attributes for creating table.
In persons table we want to make PERSON_ID column as
autoincrement and primarykey then use id and generator tags.

<?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="com.lara.Person" table="PERSONS">


<id name="id" column="PERSON_ID">
<generator class="native"/>
</id>

<property name="personName" column="PERSON_NAME"/>


<property name="personAge" column="PERSON_AGE"/>

</class>

</hibernate-mapping>

Lara Technologies 080-41310124 12


http://javaeasytoall.com

6. Now develop one client programm

package com.lara;

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

public class Manager {


public static void main (String [] args)
{
Person p1 = new Person ();
p1.setPersonName ("RAMESH");
p1.setPersonAge (29);

// 1. Configuration
Configuration config = new Configuration ();
config.configure ();

//2. Open the session Hibernate


SessionFactory sf = config.buildSessionFactory ();
Session session = sf.openSession ();

//3. Start the Transaction


session.beginTransaction ();

//4. Use the Transaction


session.save (p1);

//5. Commit the transaction


session.getTransaction ().commit ();

//6. Close the session


session.flush ();
session.close ();
}
}

7. Now start the database (i.e MySql4) and run the program.

Lara Technologies 080-41310124 13


http://javaeasytoall.com

Updating the record in the database tjrough Hibernate:

Developing a simple helloworld stand alone application by using


MySql database.

1. Go to eclipse and create one core java related project.


2. Now update the buildpath with hibernate3.jar (i.e core hibernate) ,
jar files from lib(hibernate dependence .jar files) and the Driver jar
file.

3. Now develop hibernate.cfg.xml file inside src folder

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
com.mysql.jdbc.Driver</property
<property name="connection.url">
jdbc:mysql://localhost/lara</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

Lara Technologies 080-41310124 14


http://javaeasytoall.com

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


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

<mapping resource="com/lara/Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

4. Now create a package structure and develop a Pojo object.

We want to crate table for Person with column names as


(Person_ID, PERSON_NAME, PERSON_AGE).So first develop one Pojo
class with all these attributes

package com.lara;
public class Person
{
private int id;
private String personName;
private int personAge;

public int getId () {


return id;
}
public void setId (int id) {
this.id = id;
}
public String getPersonName () {
return personName;
}
public void setPersonName (String personName) {

Lara Technologies 080-41310124 15


http://javaeasytoall.com

this.personName = personName;
}
public int getPersonAge () {
return personAge;
}
public void setPersonAge (int personAge) {
this.personAge = personAge;
}
}

5. Now develop one hbm file for every Pojo class in one package.

In hibernate with out primary key we can’t develop any table.


In hbm file we want to take care about all attributes for creating table.
In persons table we want to make PERSON_ID column as
autoincrement and primarykey then use id and generator tags.

<?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="com.lara.Person" table="PERSONS">


<id name="id" column="PERSON_ID">
<generator class="native"/>
</id>

<property name="personName" column="PERSON_NAME"/>


<property name="personAge" column="PERSON_AGE"/>
</class>
</hibernate-mapping>

6. Now develop one client programm

package com.lara;

Lara Technologies 080-41310124 16


http://javaeasytoall.com

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

public class Manager {


public static void main (String [] args)
{
Person p1 = new Person ();
p1.setPersonName ("RAMESH");
p1.setPersonAge (29);

// 1. Configuration
Configuration config = new Configuration ();
config.configure ();

//2. Open the session Hibernate


SessionFactory sf = config.buildSessionFactory ();
Session session = sf.openSession ();

//3. Start the Transaction


session.beginTransaction ();

Person p1 = (Person)session.load(com.lara.Person.class,
new Integer(id));

//4. Use the Transaction


session.saveOrUpdate(p1);

//5. Commit the transaction


session.getTransaction ().commit ();

//6. Close the session


session.flush ();
session.close ();
}
}

7. Now start the database (i.e MySql4) and run the program.

Lara Technologies 080-41310124 17


http://javaeasytoall.com

Deleting a recrd through Hibernate program:

Developing a simple helloworld stand alone application by using


MySql database.

1. Go to eclipse and create one core java related project.


2. Now update the buildpath with hibernate3.jar (i.e core hibernate) ,
jar files from lib(hibernate dependence .jar files) and the Driver jar
file.

3. Now develop hibernate.cfg.xml file inside src folder

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
com.mysql.jdbc.Driver</property
<property name="connection.url">
jdbc:mysql://localhost/lara</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->

Lara Technologies 080-41310124 18


http://javaeasytoall.com

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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


<property name="hbm2ddl.auto">create</property>

<mapping resource="com/lara/Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

4. Now create a package structure and develop a Pojo object.

We want to crate table for Person with column names as


(Person_ID, PERSON_NAME, PERSON_AGE).So first develop one Pojo
class with all these attributes

package com.lara;
public class Person
{
private int id;
private String personName;
private int personAge;

public int getId () {


return id;
}
public void setId (int id) {
this.id = id;
}
public String getPersonName () {
return personName;

Lara Technologies 080-41310124 19


http://javaeasytoall.com

}
public void setPersonName (String personName) {
this.personName = personName;
}
public int getPersonAge () {
return personAge;
}
public void setPersonAge (int personAge) {
this.personAge = personAge;
}
}

5. Now develop one hbm file for every Pojo class in one package.

In hibernate with out primary key we can’t develop any table.


In hbm file we want to take care about all attributes for creating table.
In persons table we want to make PERSON_ID column as
autoincrement and primarykey then use id and generator tags.

<?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="com.lara.Person" table="PERSONS">


<id name="id" column="PERSON_ID">
<generator class="native"/>
</id>

<property name="personName" column="PERSON_NAME"/>


<property name="personAge" column="PERSON_AGE"/>
</class>
</hibernate-mapping>

6. Now develop one client programm

Lara Technologies 080-41310124 20


http://javaeasytoall.com

package com.lara;

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

public class Manager {


public static void main (String [] args)
{
Person p1 = new Person ();
p1.setPersonName ("RAMESH");
p1.setPersonAge (29);

// 1. Configuration
Configuration config = new Configuration ();
config.configure ();

//2. Open the session Hibernate


SessionFactory sf = config.buildSessionFactory ();
Session session = sf.openSession ();

//3. Start the Transaction


session.beginTransaction ();

Person p1 = (Person)session.load(Person.class, new


Integer(id));

//4. Use the Transaction


session.delete(p1);

//5. Commit the transaction


session.getTransaction ().commit ();

//6. Close the session


session.flush ();
session.close ();
System.out.println(“ Deleted a record from table.”);
}
}

Lara Technologies 080-41310124 21


http://javaeasytoall.com

7. Now start the database (i.e MySql4) and run the program.

How to develop in web-app:

In this application we are using Mysql4 database and we want to create table
for PRODUCTS with columns
PRODUCT_NAME,PRODUCT_PRICE,PRODUCT_QUANTITY and
PRODUCT_ID.
and we want to insert,delete and edit the already stored record.

1. Copy all relavent jar files(i.e corehibernate.jar,


hibernatedependence.jar files, driver.jar file) in to the “lib” folder
of our web application.

2. Now develop hibernate.cfg.xml in “src” folder

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
com.mysql.jdbc.Driver</property>
<property name="connection.url">
dbc:mysql://localhost/lara</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->

Lara Technologies 080-41310124 22


http://javaeasytoall.com

<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


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

<mapping resource="com/lara/Product.hbm.xml"/>

</session-factory>

</hibernate-configuration>

3. Now create one package structure in “src” folder and develop one
Pojo class.
package com.lara;

public class Product


{
private int id;
private String productName;
private double productPrice;
private int productQuantity;

public int getId() {


return id;
}
public void setId(int id) {

Lara Technologies 080-41310124 23


http://javaeasytoall.com

this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public int getProductQuantity() {
return productQuantity;
}
public void setProductQuantity(int productQuantity) {
this.productQuantity = productQuantity;
}
}

4. Now develop hbm(Product.hbm.xml) file for every Pojo class.

<?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.lara.Product" table="PRODUCTS">


<id name="id" column="PRODUCT_ID">
<generator class="native"/>
</id>

<property name="productName" column="PRODUCT_NAME"/>


<property name="productPrice" column="PRODUCT_PRICE"/>
<property name="productQuantity"
column="PRODUCT_QUANTITY"/>

Lara Technologies 080-41310124 24


http://javaeasytoall.com

</class>
</hibernate-mapping>

5. Now develop one Jsp file and use it.

index.jsp
<body>
<a href="add.jsp">INSERT</a><br>
<a href="edit.jsp">EDIT</a><br>
<a href="delete.jsp">DELETE</a><br>
</body>

add.jsp page is for inserting the values into the table.

add.jsp

<body>
<form action="InsertServlet" method="post"><br>
Name:<input type="text" name="productName"><br>
Price:<input type="text" name="productPrice"><br>
Quantity:<input type="text" name="productQuantity"><br>
<input type="submit" value="submit">
</form>
</body>

edit.jsp page is for updating the already existing record.

edit.jsp

<body>
<form action="UpdateServlet" method="post">
Id:<input type="text" name="id"><br>
Name:<input type="text" name="productName"><br>
Price:<input type="text" name="productPrice"><br>
Quantity:<input type="text" name="productQuantity"><br>
<input type="submit" value="UPDATE">
</form>
</body>

Lara Technologies 080-41310124 25


http://javaeasytoall.com

delete.jsp is for deleting the record from table.

delete.jsp

<body>
<form action="DeleteServlet" method="post">
Id:<input type="text" name="id"><br>
<input type="submit" value="DELETE">
</form>
</body>

3. Develop servlets for every jsp pages.

InsertServlet.java

package com.lara;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class InsertServlet extends javax.servlet.http.HttpServlet


implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public InsertServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException
{
String pName = request.getParameter("productName");
String pPrice = request.getParameter("productPrice");
String pQty= request.getParameter("productQuantity");
Product pdr = new Product();

Lara Technologies 080-41310124 26


http://javaeasytoall.com

pdr.setProductName(pName);
pdr.setProductPrice(Double.parseDouble(pPrice));
pdr.setProductQuantity(Integer.parseInt(pQty));

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();

session.save(pdr);

session.getTransaction().commit();

session.flush();
session.close();

PrintWriter out = response.getWriter();


out.println("PRODUCT SAVED");
out.close();
}
}

UpdateServlet.java

package com.lara;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class UpdateServlet extends javax.servlet.http.HttpServlet


implements javax.servlet.Servlet

Lara Technologies 080-41310124 27


http://javaeasytoall.com

{
static final long serialVersionUID = 1L;
public UpdateServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
String id = request.getParameter("id");
String pName = request.getParameter("productName");
String pPrice = request.getParameter("productPrice");
String pQty = request.getParameter("productQuantity");

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();
Product p1 = (Product)session.load(Product.class,
Integer.parseInt(id));

p1.setProductName(pName);
p1.setProductPrice(Double.parseDouble(pPrice));
p1.setProductQuantity(Integer.parseInt(pQty));

session.saveOrUpdate(p1);

session.getTransaction().commit();

session.flush();
session.close();

PrintWriter out = response.getWriter();


out.println("PRODUCT UPDATED");
out.println("<br><a href=index.jsp>HOME</a>");
out.close();
}

Lara Technologies 080-41310124 28


http://javaeasytoall.com

DeleteServlet.java

package com.lara;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DeleteServlet extends javax.servlet.http.HttpServlet


implements javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
public DeleteServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
String id = request.getParameter("id");

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();
Product p1 = (Product)session.load(Product.class,
Integer.parseInt(id));

session.delete(p1);

Lara Technologies 080-41310124 29


http://javaeasytoall.com

session.getTransaction().commit();

session.flush();
session.close();

PrintWriter out = response.getWriter();


out.println("PRODUCT DELETED");
out.println("<br><a href=index.jsp>HOME</a>");
out.close();
}
}

4. Now start the database(i.e MySql4) and run the “index.jsp”.

One more Example for how to devlop hibernate app in web-app by


doing all the operations i.e insert,delete,update,list,search:

In this application we are using Oracle10g database and we want to


create table for ADDRESSES with column names as ADDRESS_ID,
ADDRESS_HOUSENO, ADDRESS_STREETNO, ADDRESS_CITY,
ADDRESS_STATE, ADDRESS_COUNTRY, and
ADDRESS_PINCODENO.

hibernate.cfg.xml

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE</property>

Lara Technologies 080-41310124 30


http://javaeasytoall.com

<property name="connection.username">system</property>
<property name="connection.password">great123</property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


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

<mapping resource="com/lara/Address.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Address.java

package com.lara;

public class Address


{
private Integer Id;
private String houseNo;
private String streetNo;

Lara Technologies 080-41310124 31


http://javaeasytoall.com

private String city;


private String state;
private String country;
private long pinCodeNo;

public Integer getId() {


return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;

Lara Technologies 080-41310124 32


http://javaeasytoall.com

}
public long getPinCodeNo() {
return pinCodeNo;
}
public void setPinCodeNo(long pinCodeNo) {
this.pinCodeNo = pinCodeNo;
}
}

Address.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.lara.Address" table="ADDRESSES">


<id name="id" column="ADDRESS_ID">
<generator class="native"/>
</id>

<property name="houseNo"/>
<property name="streetNo"/>
<property name="city"/>
<property name="state"/>
<property name="country"/>
<property name="pinCodeNo"/>

</class>

</hibernate-mapping>

In hbm file we are not giving any column names for property tag then it
take defaut name as property name.

index.jsp

Lara Technologies 080-41310124 33


http://javaeasytoall.com

<body>
<a href="add.jsp">Insert</a><br>
<a href="ListServlet">LIST</a><br>
<a href="search.jsp">SEARCH</a>
</body>

add.jsp is for inserting the values into the ADDRESSES table.

add.jsp

<body>
<form action="InsertServlet" method="post">
HouseNo:<input type="text" name="houseNo"><br>
StreetNo:<input type="text" name="streetNo"><br>
City:<input type="text" name="city"><br>
State:<input type="text" name="state"><br>
Country:<input type="text" name="country"><br>
PinCodeNo:<input type="text"
name="pinCodeNo"><br>
<input type="submit" value="ADD ADDRESS">
</form>
</body>
search.jsp is for searching the particular record in the table by
selsecting the column names and giving the text to search.

search.jsp

<body>
<form action="ListServlet"/>
SearchCriteria:
<select name="searchCriteria">
<option value="id">AdressId</option>
<option value="houseNo">HouseNo</option>
<option value="streetNo">StreetNo</option>
<option value="city">City</option>
<option value="state">State</option>
<option value="country">Country</option>
<option value="pinCodeNo">

Lara Technologies 080-41310124 34


http://javaeasytoall.com

PinCodeNo</option>
</select><br>

SearchText:
<input type="text" name="searchText">
<input type="submit" value="Search">

</form>
</body>
InsertServlet.java is for inserting the values into the table. If we want to
insert the servlet then we to call save() by passing the object.

InsertServlet.java

package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class InsertServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public InsertServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String houseNo=request.getParameter("houseNo");
String streetNo=request.getParameter("streetNo");
String city=request.getParameter("city");
String state=request.getParameter("state");
String country=request.getParameter("country");
String pinCodeNo=request.getParameter("pinCodeNo");

Address adr=new Address();

Lara Technologies 080-41310124 35


http://javaeasytoall.com

adr.setCity(city);
adr.setCountry(country);
adr.setHouseNo(houseNo);
adr.setPinCodeNo(Long.parseLong(pinCodeNo));
adr.setState(state);
adr.setStreetNo(streetNo);

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(adr);
session.getTransaction().commit();
session.flush();
session.close();
PrintWriter out = response.getWriter();
out.println("ADDRESS SAVED");
out.close();
}
}

UpdateServlet.java is for editing the particular record in the table. If we


want to update the record then we want to call saveOrUpdate() by
passing the object.

UpdateServlet.java

package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class UpdateServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet

Lara Technologies 080-41310124 36


http://javaeasytoall.com

{
static final long serialVersionUID = 1L;
public UpdateServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String id = request.getParameter("recordId");
String houseNo=request.getParameter("houseNo");
String streetNo=request.getParameter("streetNo");
String city=request.getParameter("city");
String state=request.getParameter("state");
String country=request.getParameter("country");
String pinCodeNo=request.getParameter("pinCodeNo");

Address adr=new Address();

adr.setId(new Integer(id));
adr.setCity(city);
adr.setCountry(country);
adr.setHouseNo(houseNo);
adr.setPinCodeNo(Long.parseLong(pinCodeNo));
adr.setState(state);
adr.setStreetNo(streetNo);

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();

session.saveOrUpdate(adr);

session.getTransaction().commit();

session.flush();
session.close();

Lara Technologies 080-41310124 37


http://javaeasytoall.com

PrintWriter out = response.getWriter();


out.println("ADDRESS SAVED<br>");
out.println("<a href='index.jsp'>Home</a>");
out.println("<a href='ListServlet'>ListRecordHome</a>");
out.close();
}
}

ListServlet.java is for listing all the records from table. If we want to list
all the records then we want to use Criteria interface or Query
interface. In this application we are using Criteria.If we want to create
object for Criteria interface then there is a method createCriteria ()
which there inside the session class.

Eg: session.createCriteria(Address.class);

ListServlet.java

package com.lara;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Expression;

public class ListServlet extends javax.servlet.http.HttpServlet implements


javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
public ListServlet() {
super();
}

Lara Technologies 080-41310124 38


http://javaeasytoall.com

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException
{
Address add= new Address();
PrintWriter out = response.getWriter();
String sc = request.getParameter("searchCriteria");
String st = request.getParameter("searchText");
out.println("<table border='1'>");
out.println("<tr>");
out.println("<td>");
out.println("<b>ID</b>");
out.println("</td>");
out.println("<td>");
out.println("<b>HOUSENO</b>");
out.println("</td>");
out.println("<td>");
out.println("<b>STREETNO</b>");
out.println("</td>");
out.println("<td>");
out.println("<b>CITY</b>");
out.println("</td>");
out.println("<td>");
out.println("<b>STATE</b>");
out.println("</td>");
out.println("<td>");
out.println("<b>COUNTRY</b>");
out.println("</td>");
out.println("<td>");
out.println("<b>PINCODENO</b>");
out.println("</td>");
out.println("</tr>");

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();

Lara Technologies 080-41310124 39


http://javaeasytoall.com

Criteria ctr = session.createCriteria(Address.class);


ctr.add(Expression.eq(sc, st));

List list = ctr.list();

Expression.sql(sc+"='"+st+"'");

for(int i=0;i<list.size();i++)
{
add = (Address)list.get(i);
out.println("<tr>");
out.println("<td>");
out.println("<a href='DetailedServlet?recordId="
+add.getId()+"'>");
out.println(add.getId());
out.println("</a>");
out.println("</td>");
out.println("<td>");
out.println(add.getHouseNo());
out.println("</td>");
out.println("<td>");
out.println(add.getStreetNo());
out.println("</td>");
out.println("<td>");
out.println(add.getCity());
out.println("</td>");
out.println("<td>");
out.println(add.getState());
out.println("</td>");
out.println("<td>");
out.println(add.getCountry());
out.println("</td>");
out.println("<td>");
out.println(add.getPinCodeNo());
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("<a href='index.jsp'>Home</a>");

Lara Technologies 080-41310124 40


http://javaeasytoall.com

session.getTransaction().commit();
session.flush();
session.close();
}
}

DetailedServlet.java is for if we select one record then it want to display


all the columns from the table.for this we want to use load () method
which there inside the session class.

DetailedServlet.java

package com.lara;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class DetailedServlet extends javax.servlet.http.HttpServlet


implements javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
public DetailedServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException
{
String recordId = request.getParameter("recordId");

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();

Lara Technologies 080-41310124 41


http://javaeasytoall.com

Session session = sf.openSession();

session.beginTransaction();

Address add = (Address)session.load(Address.class,


new Integer(recordId));
PrintWriter out = response.getWriter();
out.println("HouseNo:"+add.getHouseNo()+"<br>");
out.println("StreetNo:"+add.getStreetNo()+"<br>");
out.println("City:"+add.getCity()+"<br>");
out.println("State:"+add.getState()+"<br>");
out.println("Country:"+add.getCountry()+"<br>");
out.println("PINCODENO:"+add.getPinCodeNo()+"<br>");
out.println("<a href='DisplayForEdit?recordId="
+add.getId()+"'>Edit</a>");
out.println("<a href='DeleteServlet?recordId="
+add.getId()+"'>Delete</a>");
out.println("<a href='index.jsp'>Home</a>");
out.println("<a href='ListServlet'>ListRecordHome</a>");

session.getTransaction().commit();

session.flush();
session.close();
}
}

DeleteServlet.java is for deleting the particular record.If we want to


delete one record then we want to call the delete() by passing the object .

DeleteServlet.java

package com.lara;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Lara Technologies 080-41310124 42


http://javaeasytoall.com

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class DeleteServlet extends javax.servlet.http.HttpServlet


implements javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
public DeleteServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException
{
String id = request.getParameter("recordId");
Address add = new Address();
add.setId(new Integer(id));

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();

session.delete(add);

session.getTransaction().commit();

session.flush();
session.close();

PrintWriter out = response.getWriter();


out.println("ADDRESS DELETED");
out.println("<a href='index.jsp'>Home</a>");
out.println("<a href='ListServlet'>ListRecordHome</a>");
out.close();
}

Lara Technologies 080-41310124 43


http://javaeasytoall.com

DisplayForEdit.java is for modifying the particular record in the table.

DisplayForEdit.java

package com.lara;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class DisplayForEdit extends javax.servlet.http.HttpServlet


implements javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
public DisplayForEdit() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException
{
String recordId = request.getParameter("recordId");
Configuration config = new Configuration();
config.configure();

SessionFactory sf = config.buildSessionFactory();

Session session = sf.openSession();

session.beginTransaction();

PrintWriter out = response.getWriter();

Lara Technologies 080-41310124 44


http://javaeasytoall.com

Address add = (Address)session.load(Address.class,


new Integer(recordId));
out.println("<form action='UpdateServlet' method='post'>");
out.println("<input type='hidden' name='recordId' value='"
+add.getId()+"'><br>");
out.println("HouseNo:");
out.println("<input type='text' name='houseNo' value='"
+add.getHouseNo()+"'><br>");
out.println("StreetNo:");
out.println("<input type='text' name='streetNo' value='"
+add.getStreetNo()+"'><br>");
out.println("City");
out.println("<input type='text' name='city' value='"
+add.getCity()+"'><br>");
out.println("State");
out.println("<input type='text' name='state' value='"
+add.getState()+"'><br>");
out.println("Country");
out.println("<input type='text' name='country' value='"
+add.getCountry()+"'><br>");
out.println("PinCodeNo:");
out.println("<input type='text' name='pinCodeNo' value='"
+add.getPinCodeNo()+"'><br>");
out.println("<input type='submit' value='UPDATE'>");
out.println("</form>");

session.getTransaction().commit();

session.flush();
session.close();
}
}

What are all the algorithms for attribute “class” of “generator ” tag of “id”
tag ?
 The types of algorithms are:
1. hilo
2. seqhilo

Lara Technologies 080-41310124 45


http://javaeasytoall.com

3. uuid
4. guid
5. sequence
6. identity
7. select

Eg: For testing the algorithms using Oracle10g database

hibernate.cg.xml

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">great123</property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">

Lara Technologies 080-41310124 46


http://javaeasytoall.com

org.hibernate.cache.NoCacheProvider </property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


<property name="hbm2ddl.auto">create</property>

<mapping resource="com/lara/Book.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Book.java

package com.lara;

public class Book


{
private Integer id;
private String bookName;
private String bookAuther;
private Double bookPrice;

public Integer getId() {


return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookAuther() {
return bookAuther;

Lara Technologies 080-41310124 47


http://javaeasytoall.com

}
public void setBookAuther(String bookAuther) {
this.bookAuther = bookAuther;
}

public Double getBookPrice() {


return bookPrice;
}
public void setBookPrice(Double bookPrice) {
this.bookPrice = bookPrice;
}

Book.hbm.xml

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

<hibernate-mapping>

<class name="com.lara.Book" table="BOOKS">


<id name="id" column="PRODUCT_ID">
<generator class="identity"/>
</id>

<property name="bookName"/>
<property name="bookAuther"/>
<property name="bookPrice"/>

</class>

</hibernate-mapping>

addBook.jsp

<body>
<form action=” AddBookServlet” method=”post”>

Lara Technologies 080-41310124 48


http://javaeasytoall.com

Id :<input type=”text” name=”id”/><br>


BookName :<input type=”text” name=”name”/><br>
BookAuther :<input type=”text” name=”auther”/><br>
BookPrice :<input type=”text” name=”price”/><br>
<input type=”submit” value=”submit”/>
</form>

</body>

AddBookServlet.java

package com.lara;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class AddBookServlet


{
public void AddBookServlet()
{
super();
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException
{
String id=request.getParameter(“id”);
String name=request.getParameter(“name”);
String auther=request.getParameter(“auther”);
String price=request.getParameter(“price”);

Book book = new Book();


book.setId(100);

Lara Technologies 080-41310124 49


http://javaeasytoall.com

book.setBookName("JAVA");
book.setBookAuther("MAHESH");
book.setBookPrice(450.50);

Configuration config = new Configuration();


config.configure("config/hibernate.cfg.xml");

SessionFactory sf = config.buildSessionFactory();

Session session = sf.openSession();

session.beginTransaction();

session.save(book);

session.getTransaction().commit();

session.flush();
session.close();

PrintWriter out=response.getWriter();
Out.println(“check in the database.”);
}
}

All algorithms will not support all the databases only few algorithms
only support particular databases.

AlgoritmName Mysql4 Oracle10g


hilo Supports Supports
seqhilo Not supports Supports
uuid Not supports Not supports
guid Not supports Not supports
Sequence Not supports Supports
identity Supports Notsupports

Among these some more algorithms is there they are


native,assigned,increment these algorithms will support all the
databases.

Lara Technologies 080-41310124 50


http://javaeasytoall.com

How to separate cfg.xml from src folder to separate folder.

Create one folder where ever and copy that cfg file into that folder then
come to the program and at the time of configuration give the path of the
folder.

EG:
Src|
|----cfg|
|----hibernate.cfg.xml
Now come to the program
Configuration config = new Configuration();
config.configure("config/hibernate.cfg.xml");

Cascade types:

all,create,merge,save-update,delete,lock,refresh,evict,replicate.

constrained (optional) specifies that a foreign key constraint on the primary


key of the mapped table references the table of the associated class. This
option affects the order in which save() and delete() are cascaded, and
determines whether the association may be proxied (it is also used by the
schema export tool).

If we give constrained=”false” then in USER_DETAILS table we will not


get refrencekey i.e foreignkey but we will get data
The generated query is
create table USER_DETAILS
(
“USER_ID” VARCHAR2(255),
“USER_EDUCATION” VARCHAR2(255),
“USER_DESIGNATION” VARCHAR2(255),
“USER_ADDRESS” VARCHAR2(255),
PRIMARYKEY(“USER_ID”)ENABLE
)
If we give constrained=”true” then we will get refrencekey i.e foreignkey
and data

Lara Technologies 080-41310124 51


http://javaeasytoall.com

create table USER_DETAILS


(
“USER_ID” VARCHAR2(255)NOT NULL ENABLE,
“USER_EDUCATION” VARCHAR2(255),
“USER_DESIGNATION” VARCHAR2(255),
“USER_ADDRESS” VARCHAR2(255),
PRIMARYKEY(“USER_ID”)ENABLE
CONSTRAINT “FK24CC75E74607B17”
FOREIGNKEY(“USER_ID”)
REFERENCES “USERS”(“USER_ID”) ENABLE

Mappings are mainly threee types they are:

1. Relational Mapping
(a) One-to-One Mapping
(b) One-to-Many and Many-to-one Mapping
(c) Many-to-many Mapping
2. Polymorphic Mapping.
(a) One table per Class hierarchy
(b) One table per Sub-Class
(c) One table per Concreate-Class
3. Component Mapping.

1.(a) One-to-One Mapping:

hibernate.cfg.xml

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


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

<hibernate-configuration>

Lara Technologies 080-41310124 52


http://javaeasytoall.com

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">great123</property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


<property name="hbm2ddl.auto">create</property>

<mapping resource="com/lara/Person.hbm.xml"/>
<mapping resource="com/lara/ Mail.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Person.java

Lara Technologies 080-41310124 53


http://javaeasytoall.com

package com.lara;

public class Person


{
private String personId;
private String personFirstName;
private String personLastName;
private Integer personAge;
private Mail mailId;

public String getPersonId () {


return personId;
}
public void setPersonId(String userId) {
this.personId = personId;
}
public String getPersonFirstName() {
return personFirstName;
}
public void setPersonFirstName(String personFirstName) {
this.personFirstName = personFirstName;
}
public String getPersonLastName() {
return personLastName;
}
public void setPersonLastName(String personLastName) {
this.personLastName = personLastName;
}
public Integer getPersonAge() {
return personAge;
}
public void setPersonAge(Integer personAge) {
this.personAge = personAge;
}

public Mail getMailId() {


return mailId;
}
public void setMailId(Mail mailId) {

Lara Technologies 080-41310124 54


http://javaeasytoall.com

this.mailId = mailId;
}
}

Mail.java

package com.lara;

public class Mail


{
private String mailId;
private Person person;
private String password;
private Date createdTime;
private String personId;

public String getMailId() {


return mailId;
}
public void setMailId(String userId) {
this. mailId = mailId;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this. person = person;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}

Lara Technologies 080-41310124 55


http://javaeasytoall.com

public String getPersonId() {


return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
}

User.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.lara.Person" table="PERSONS">


<id name=" personId " column="PERSON_ID">
<generator class=”assigned”/>
</id>

<property name="personFirstName" column=" PERSON


_FIRST_NAME"/>
<property name="personLastName" column=" PERSON
_LAST_NAME"/>
<property name="personAge" column=" PERSON _AGE"/>
<property name="mailId" column=" PERSON _EMAIL"/>

<on-to-one name="mail" class="com.lara.Mail" cascade="all"/>

</class>

</hibernate-mapping>

Mail.hbm.xml

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


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

Lara Technologies 080-41310124 56


http://javaeasytoall.com

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

<hibernate-mapping>

<class name="com.lara.Mail" table="MAILS">


<id name="mailId" column="MAIL_ID">
<generator class="foreign">
<param name="property">Person</param>
</generator>
</id>

<property name=" password " column="PASSWORD "/>


<property name=" createdTime " column="USER_ EDUC "/>
<property name=" personId " column="USER_DESIGNATION"/>

<on-to-one name="Person" class="com.lara.Person"


constrained="true"/>

</class>

</hibernate-mapping>

Manager.java

package com.lara;

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

public class Manager


{
public static void main(String[] args)
{
Mail mail = new Mail();
mail.setMailId ("abc@abc.com");
mail.setPerson (p1);
mail.setPassword("abcxyz");
mail.setCreatedTime("22-jan-2009");

Lara Technologies 080-41310124 57


http://javaeasytoall.com

mail.setPersonId("p101");

Person p1= new Person();


p1.setPersonId("p101");
p1.setPersonFirstName("abc");
p1.setPersonLastName("def");
p1.setPersonAge (28);
p1.setMailId(("abc@abc.com");

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();

session.save(p1);

session.getTransaction().commit();

session.flush();
session.close();
}

}
Example2:

hibernate.cfg.xml

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


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

<hibernate-configuration>

<session-factory>

Lara Technologies 080-41310124 58


http://javaeasytoall.com

<!-- Database connection settings -->


<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">great123</property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


<property name="hbm2ddl.auto">create</property>

<mapping resource="com/lara/User.hbm.xml"/>
<mapping resource="com/lara/ UserDetails.hbm.xml"/>

</session-factory>

</hibernate-configuration>

User.java

package com.lara;

Lara Technologies 080-41310124 59


http://javaeasytoall.com

public class User


{
private String userId;
private String userFirstName;
private String userLastName;
private Integer userAge;
private String userEmail;
private String userMobileNo;
private UserDetails userDetails;

public String getUserId() {


return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserFirstName() {
return userFirstName;
}
public void setUserFirstName(String userFirstName) {
this.userFirstName = userFirstName;
}
public String getUserLastName() {
return userLastName;
}
public void setUserLastName(String userLastName) {
this.userLastName = userLastName;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}

Lara Technologies 080-41310124 60


http://javaeasytoall.com

public String getUserMobileNo() {


return userMobileNo;
}
public void setUserMobileNo(String userMobileNo) {
this.userMobileNo = userMobileNo;
}
public UserDetails getUserDetails() {
return userDetails;
}
public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}
}

UserDetails.java

package com.lara;

public class UserDetails


{
private String userId;
private User user;
private String educ;
private String designation;
private String address;

public String getUserId() {


return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getEduc() {
return educ;

Lara Technologies 080-41310124 61


http://javaeasytoall.com

}
public void setEduc(String educ) {
this.educ = educ;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

User.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.lara.User" table="USERS">


<id name="userId" column="USER_ID">
<generator class=”assigned”/>
</id>

<property name="userFirstName" column="USER_FIRST_NAME"/>


<property name="userLastName" column="USER_LAST_NAME"/>
<property name="userAge" column="USER_AGE"/>
<property name="userEmail" column="USER_EMAIL"/>
<property name="userMobileNo" column="USER_MOBILE_NO"/>

<on-to-one name="userDetails" class="com.lara.UserDetails"


cascade="all"/>

Lara Technologies 080-41310124 62


http://javaeasytoall.com

</class>
</hibernate-mapping>

UserDetails.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.lara.UserDetails" table="USER_DETAILS">


<id name="userId" column="USER_ID">
<generator class="foreign">
<param name="property">user</param>
</generator>
</id>

<property name=" user " column="USER "/>


<property name=" educ " column="USER_ EDUC "/>
<property name=" designation " column="USER_DESIGNATION"/>
<property name=" address " column="USER_ADDRESS"/>

<on-to-one name="user" class="com.lara.User" constrained="true"/>

</class>

</hibernate-mapping>

Manager.java

package com.lara;

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

public class Manager

Lara Technologies 080-41310124 63


http://javaeasytoall.com

{
public static void main(String[] args)
{
User user = new User();
user.setUserId("index101");
user.setUserAge(23);
user.setUserEmail("manikanta@gmail.com");
user.setUserFirstName("MANIKANTA");
user.setUserLastName("CHOUDHARY");
user.setUserMobileNo("9986340298");

UserDetails ud = new UserDetails();


ud.setAddress("TPT");
ud.setDesignation("PM");
ud.setEduc("BTech");
ud.setUser(user);
user.setUserDetails(ud);

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();

session.save(user);

session.getTransaction().commit();

session.flush();
session.close();
}

Foreign key development:

Lara Technologies 080-41310124 64


http://javaeasytoall.com

Usually foreign key is used for to join the two tables In this example we
want to join User and UserDetails. In this we are using one-to-one join if one
modification is done in one table then that modifications will reflect back
to another table also.

<on-to-one name=”” class=”” contrained=”” or cascade=””/>

name: The name of the property.

class (optional - defaults to the property type determined by reflection): The


name of the associated class.

cascade (optional) specifies which operations should be cascaded from the


parent object to the associated object.

1.(b) one-to-many development:

on-to-many is used for in one table one column is referring to multiple


columns in the other table
In this eg;BATCHES table BATCH_ID is refered by so many columns from
the STUDENTS TABLE

hibernate.cfg.xml

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


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

Lara Technologies 080-41310124 65


http://javaeasytoall.com

<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">great123</property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


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

<mapping resource="com/lara/Batch.hbm.xml"/>
<mapping resource="com/lara/Student.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Student.java

package com.lara;

public class Student


{

Lara Technologies 080-41310124 66


http://javaeasytoall.com

private Integer id;


private String firstName;
private String lastName;
private Integer age;
private Batch batch;

public Integer getId() {


return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
}

Batch.java
package com.lara;

Lara Technologies 080-41310124 67


http://javaeasytoall.com

import java.util.HashSet;
import java.util.Set;

public class Batch


{
private Integer id;
private String batchName;
private Set students = new HashSet();

public Integer getId() {


return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public Set getStudents() {
return students;
}
public void setStudents(Set students) {
this.students = students;
}
public void addStudentToBatch(Student std)
{
if(students == null)
{
students = new HashSet();
}
students.add(std);
}

Batch.hbm.xml

Lara Technologies 080-41310124 68


http://javaeasytoall.com

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


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

<hibernate-mapping package="com.lara">

<class name="Batch" table="BATCHES">


<id name="id" column="BATCH_ID">
<generator class="assigned"/>
</id>
<property name="batchName" column="BATCH_NAME"/>
<set name="students" cascade="all">
<key column="BATCH_ID"/>
<one-to-many class="Student"/>
</set>
</class>

<class name="Student" table="STUDENTS">


<id name="id" column="STUDENT_ID">
<generator class="native"/>
</id>

<property name="firstName" column="STUDENT_FIRST_NAME"/>


<property name="lastName" column="STUDENT_LAST_NAME"/>
<property name="age" column="STUDENT_AGE"/>

<many-to-one name="batch" column="BATCH_ID" class="Batch"/>

</class>

</hibernate-mapping>

Manager.java

Lara Technologies 080-41310124 69


http://javaeasytoall.com

package com.lara;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Manager


{
public static void main(String[] args)
{
//1.Insertion

Batch batch = new Batch();


batch.setId(3);
batch.setBatchName("JAVA/J2EE");

Student std1 = new Student();


std1.setFirstName("MANI");
std1.setLastName("LARA");
std1.setAge(23);
std1.setBatch(batch);
batch.addStudentToBatch(std1);

Student std2 = new Student();


std2.setFirstName("RAMU");
std2.setLastName("LARA");
std2.setAge(23);
std2.setBatch(batch);
batch.addStudentToBatch(std2);

//CONFIGURATION OF HIBERNATE

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();

Lara Technologies 080-41310124 70


http://javaeasytoall.com

Session session = sf.openSession();

session.beginTransaction();

//1.INSERTION
/*
session.save(batch);
session.getTransaction().commit();
*/

// Randomly UPDATE
/*
Batch batch = (Batch)session.load(Batch.class,3);
Iterator it = batch.getStudents().iterator();
Student std = null;
if(it.hasNext())
{
std = (Student) it.next();
}
std.setFirstName("CHAGED MANIKANTA");
session.saveOrUpdate(std);
session.getTransaction().commit();
*/

//PARTICULAR RECORD UPDATE


/*
Batch batch = (Batch)session.load(Batch.class,3);
Iterator it = batch.getStudents().iterator();
Student std = null;
while(it.hasNext())
{
std = (Student)it.next();
if(std.getId() == 2)
{
break;
}

}
std.setFirstName("CHANGED AGAIN MANIKANTA");

Lara Technologies 080-41310124 71


http://javaeasytoall.com

session.saveOrUpdate(std);
*/

//UPDATE WITH OUT BATCH


/*
Student std = (Student)session.load(Student.class,1);
std.setFirstName("NEW-CHOUDHARY");
session.saveOrUpdate(std);
*/

//READING THE RECORDS FROM TABLE

List batches = (List)session.createCriteria(Batch.class).list();


Batch batch = null;
Student std = null;
Iterator it = null;
for(int i=0;i<batches.size();i++)
{
batch = (Batch)batches.get(i);
it=batch.getStudents().iterator();
while(it.hasNext())
{
std = (Student)it.next();
System.out.println(batch.getId()
+":"+std.getFirstName());
}
}
session.getTransaction().commit();
session.flush();
session.close();
}
}

//DELETEING THE Record From TABLE

/*
Batch batch = (Batch) session.load(Batch.class, 3);
Student std = null;
Iterator it = batch.getStudents().iterator();

Lara Technologies 080-41310124 72


http://javaeasytoall.com

while(it.hasNext())
{
std = (Student)it.next();
if(std.getId() == 2)
{
break;
}
}
batch.getStudents().remove(std);
session.delete(std);
*/

1.(c) many-to-many development:

hibernate.cfg.xml

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
om.mysql.jdbc.Driver</property>
<property name="connection.url">
jdbc:mysql://localhost/lara</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

Lara Technologies 080-41310124 73


http://javaeasytoall.com

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider </property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


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

<mapping resource="com/lara/Batch.hbm.xml"/>
<mapping resource="com/lara/Student.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Student.java

package com.lara;

import java.util.HashSet;
import java.util.Set;

public class Student


{
private Integer id;
private String stdName;
private String stdQualification;
private Set batch = new HashSet();

public Integer getId() {


return id;
}

Lara Technologies 080-41310124 74


http://javaeasytoall.com

public void setId(Integer id) {


this.id = id;
}
public String getStdName() {
return stdName;
}
public void setStdName(String stdName) {
this.stdName = stdName;
}
public String getStdQualification() {
return stdQualification;
}
public void setStdQualification(String stdQualification) {
this.stdQualification = stdQualification;
}
public Set getBatch() {
return batch;
}
public void setBatch(Set batch) {
this.batch = batch;
}
}

Batch.java

package com.lara;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Batch
{
private Integer id;
private String batchName;
private Date startDate;
private Integer duration;
private Integer fee;
private Set participents = new HashSet();

Lara Technologies 080-41310124 75


http://javaeasytoall.com

public Integer getId() {


return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public Integer getFee() {
return fee;
}
public void setFee(Integer fee) {
this.fee = fee;
}
public Set getParticipents() {
return participents;
}
public void setParticipents(Set participents) {
this.participents = participents;
}
public void addParticipentsToBatch(Student std)
{
participents.add(std);

Lara Technologies 080-41310124 76


http://javaeasytoall.com

std.getBatch().add(this);
}
public void removeParticipentsFromBatch(Student std)
{
participents.remove(std);
std.getBatch().remove(this);
}
}

Student.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 package="com.lara">

<class name="Student" table="STUDENTS">


<id name="id" column="STD_ID">
<generator class="assigned"/>
</id>

<property name="stdName" column="STUDENT_NAME"/>


<property name="stdQualification" column=
"BATCH_QUALIFICATION"/>

<set name="batch" table="B_S_JOIN">


<key column="STD_ID"/>
<many-to-many column="BATCH_ID" class="Batch"/>
</set>
</class>

</hibernate-mapping>

Batch.hbm.xml

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


<!DOCTYPE hibernate-mapping PUBLIC

Lara Technologies 080-41310124 77


http://javaeasytoall.com

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


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

<hibernate-mapping package="com.lara">

<class name="Batch" table="BATCHES">


<id name="id" column="BATCH_ID">
<generator class="assigned"/>
</id>

<property name="batchName" column="BATCH_NAME"/>


<property name="startDate" column="BATCH_STARTDATE"/>
<property name="duration" column="BATCH_DURATION"/>
<property name="fee" column="BATCH_FEE"/>

<set name="participents" table="B_S_JOIN" inverse="true">


<key column="BATCH_ID"/>
<many-to-many column="STD_ID" class="Student"/>
</set>

</class>

</hibernate-mapping>

Manager.java

package com.lara;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

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

public class Manager


{
public static void main(String args[])

Lara Technologies 080-41310124 78


http://javaeasytoall.com

{
//add();
//readBatchWiseStudents(3);
//UpdateParticularStudent(3,102,"Changed MANIKANTA");
deletingRecord(4,104);
}
private static void add()
{
Batch b1 = new Batch();
b1.setId(3);
b1.setBatchName("REGULAR JAVA");
b1.setDuration(120);
b1.setFee(5000);

Date date = new Date();


Date startDay = new Date(date.getTime() +
7*24*60*60*1000);
b1.setStartDate(startDay);

Batch b2 = new Batch();


b2.setId(4);
b2.setBatchName("SPRING");
b2.setDuration(30);
b2.setFee(1000);
Date SpringstartDay = new Date(date.getTime() +
10*24*60*60*1000);
b2.setStartDate(SpringstartDay);

Student std = new Student();


std.setId(101);
std.setStdName("RAMESH");
std.setStdQualification("B.Tech");
b1.addParticipentsToBatch(std);
b2.addParticipentsToBatch(std);

Student std1 = new Student();


std1.setId(102);
std1.setStdName("MANIKANTA");
std1.setStdQualification("B.Tech");
b1.addParticipentsToBatch(std1);

Lara Technologies 080-41310124 79


http://javaeasytoall.com

Student std2 = new Student();


std2.setId(103);
std2.setStdName("NAGESH");
std2.setStdQualification("B.Tech");
b1.addParticipentsToBatch(std2);

Student std3 = new Student();


std3.setId(104);
std3.setStdName("RAMU");
std3.setStdQualification("Bsc");
b2.addParticipentsToBatch(std3);

SessionFactory sf = getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(b1);
session.save(b2);
session.save(std);
session.save(std1);
session.save(std2);
session.save(std3);
session.getTransaction().commit();
session.flush();
session.close();
}

private static SessionFactory getSessionFactory()


{
Configuration config = new Configuration();
config.configure();
SessionFactory sf = config.buildSessionFactory();
return sf;
}

private static void readBatchWiseStudents(int i)


{
SessionFactory sf = getSessionFactory();
Session session = sf.openSession();

Lara Technologies 080-41310124 80


http://javaeasytoall.com

session.beginTransaction();
Batch b = (Batch)session.load(Batch.class, i);
Set students = b.getParticipents();
Iterator allStudents = students.iterator();
Student std = null;
while(allStudents.hasNext())
{
std = (Student)allStudents.next();
System.out.println(std.getId()+":"+std.getStdName());

}
session.getTransaction().commit();
session.flush();
session.close();
}

private static void UpdateParticularStudent(int batchNo,int


studentNo,String modifiedName)
{
SessionFactory sf = getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Batch batch = (Batch)session.load(Batch.class,batchNo);
Iterator it = batch.getParticipents().iterator();
Student std = null;
while(it.hasNext())
{
std = (Student)it.next();
if(std.getId() == studentNo)
{
break;
}
}
std.setStdName(modifiedName);
session.saveOrUpdate(std);
session.getTransaction().commit();
session.flush();
session.close();
}

Lara Technologies 080-41310124 81


http://javaeasytoall.com

private static void deletingRecord(int batchNo,int studentNo)


{
SessionFactory sf = getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Batch batch = (Batch)session.load(Batch.class, batchNo);
Student std = null;
Iterator it = batch.getParticipents().iterator();
while(it.hasNext())
{
std = (Student)it.next();
if(std.getId() == studentNo)
{
break;
}
}
batch.getParticipents().remove(std);
session.delete(std);
session.getTransaction().commit();
session.flush();
session.close();
}
}

Example: programaticllydeclaring properties

Developing an application without configuration file. Keeping inside ur


client program by creating config object.
Create one application and update the buildpath with relavent JAR files.

Now create a package structure and develop a Pojo object.

We want to crate table for Person with column names as


(Person_ID, PERSON_NAME, PERSON_AGE).So first develop one Pojo
class with all these attributes

package com.lara;

Lara Technologies 080-41310124 82


http://javaeasytoall.com

public class Person


{
private Integer id;
private String personName;
private Integer personAge;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
}

Now develop one hbm file for every Pojo class in one package.

In hibernate with out primary key we can’t develop any table.


In hbm file we want to take care about all attributes for creating table.
In persons table we want to make PERSON_ID column as
autoincrement and primarykey then use id and generator tags.

<?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>

Lara Technologies 080-41310124 83


http://javaeasytoall.com

<class name="com.lara.Person" table="PERSONS">


<id name="id" column="PERSON_ID">
<generator class="native"/>
</id>

<property name="personName" column="PERSON_NAME"/>


<property name="personAge" column="PERSON_AGE"/>

</class>

</hibernate-mapping>

Now develop one client programm

package com.lara;

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

public class Manager {


public static void main (String [] args)
{
Person p1 = new Person ();
p1.setPersonName ("RAMESH");
p1.setPersonAge (29);

Configuration config = new Configuration ();


config.setProperty("connection.driver_class",
“oracle.jdbc.driver.OracleDriver”);
config.setProperty("connection.url ",
“jdbc:oracle:thin:@localhost:1521:XE”);
config.setProperty("connection.username ", “system”);
config.setProperty("connection.password ", “great123”);
config.setProperty("connection.pool_size ", “1”);
config.setProperty("dialec",
“org.hibernate.dialect.OracleDialect”);
config.setProperty("current_session_context_class ",
“thread”);

Lara Technologies 080-41310124 84


http://javaeasytoall.com

config.setProperty("cache.provider_class ",
“org.hibernate.cache.NoCacheProvider”);
config.setProperty("show_sql ", “true”);
config.setProperty("hbm2ddl.auto ", “update”);

config.addResource(“com/lara/Person.hbm.xml”);
System.out.println(“Hibernate got configured.”);

SessionFactory sf = config.buildSessionFactory ();


System.out.println(“SessionFactory got configured.”);

Session session = sf.openSession ();


System.out.println(“session object got configured.”);

session.beginTransaction ();
System.out.println(“transaction started..”);

session.saveOrUpdate(p1);
System.out.println(“person object saved/updated.”);

session.getTransaction ().commit ();


System.out.println(“transaction committed..”);

session.flush ();
System.out.println(“session got flushed..”);
session.close ();
System.out.println(“session got closed..”);
}
}

Now start the database (i.e Oracle) and run the program.

Example2 programaticllydeclaring properties

Lara Technologies 080-41310124 85


http://javaeasytoall.com

create a package structure and develop a Pojo object.

package com.lara;

public class Person


{
private String orderId;
private String orderName;
private Date orderDate;
private String orderDescription;
private Double orderPrice;
private String orderBy;

public Striong getOrderId() {


return orderId;
}
public void setOrderId(int orderId) {
this. orderId= orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName (String orderName) {
this.orderName = orderName;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate= orderDate;
}
public Striong getOrderDescription() {
return orderDescription;
}
public void setOrderDescription(int orderDescription) {
this.orderDescription = orderDescription;
}
public Double getOrderPrice() {
return orderPrice;

Lara Technologies 080-41310124 86


http://javaeasytoall.com

}
public void setOrderPrice(int orderPrice) {
this. orderPrice = orderPrice;
}

public String getOrderBy() {


return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}

Now develop one hbm file for every Pojo class in one package.

<?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="com.lara.Order" table="ORDERS">


<id name="orderId" column="ORDER_ID">
<generator class="native"/>
</id>

<property name="orderName" column="ORDER_NAME"/>


<property name="orderDate" column="ORDER_DATE"/>
<property name="orderDescription" column="ORDER_DESC"/>
<property name="orderPrice" column="ORDER_PRICE"/>
<property name="orderBy" column="ORDER_BY"/>

</class>

</hibernate-mapping>

Now develop one client programm

Lara Technologies 080-41310124 87


http://javaeasytoall.com

package com.lara;

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

public class Manager {


public static void main (String [] args)
{
Order order= new Order();
Order.setOredrId(“ord101”);
Order.setOredrName(“TV”);
Order.setOredrDate(new Date());
Order.setOredrDescription(“Sony TV”);
Order.setOredrPeice(12000.00);
Order.setOredrBy(“LARA”);

Configuration config = new Configuration ();


config.setProperty("connection.driver_class",
“oracle.jdbc.driver.OracleDriver”);
config.setProperty("connection.url ",
“jdbc:oracle:thin:@localhost:1521:XE”);
config.setProperty("connection.username ", “system”);
config.setProperty("connection.password ", “great123”);
config.setProperty("connection.pool_size ", “1”);
config.setProperty("dialec",
“org.hibernate.dialect.OracleDialect”);
config.setProperty("current_session_context_class ",
“thread”);
config.setProperty("cache.provider_class ",
“org.hibernate.cache.NoCacheProvider”);
config.setProperty("show_sql ", “true”);
config.setProperty("hbm2ddl.auto ", “update”);

config.addResource(“com/lara/Person.hbm.xml”);
System.out.println(“Hibernate got configured.”);

SessionFactory sf = config.buildSessionFactory ();


System.out.println(“SessionFactory got configured.”);

Lara Technologies 080-41310124 88


http://javaeasytoall.com

Session session = sf.openSession ();


System.out.println(“session object got configured.”);

session.beginTransaction ();
System.out.println(“transaction started..”);

session.save(order);
System.out.println(“person object saved.”);

session.getTransaction ().commit ();


System.out.println(“transaction committed..”);

session.flush ();
System.out.println(“session got flushed..”);
session.close ();
System.out.println(“session got closed..”);
}

// To read all the records


/*
List<Order> list = session.createCriteria(com.lara.Orser.class).list();
for(Order order : list)
{
System.out.println(order.getOrderId());
System.out.println(order.getOrderName());
System.out.println(order.getOrderDate());
System.out.println(order.getOrderDescription());
System.out.println(order.getOrderPrice());
System.out.println(order.getOrderBy());
}
(OR)
Criteria ctr = session.createCriteria(com.lara.Order.class);
Ctr.add(Restrictions.eq(“orderBy”, abc));
List<Order>
For(Order order : list)
{

Lara Technologies 080-41310124 89


http://javaeasytoall.com

System.out.println(order.getOrderId());
System.out.println(order.getOrderName());
System.out.println(order.getOrderDate());
System.out.println(order.getOrderDescription());
System.out.println(order.getOrderPrice());
System.out.println(order.getOrderBy());
}

*/
//same can be achieved through query
/*
Criteria ctr = session.createCriteria(com.lara.Order.class);
Ctr.add(Restrictions.sqlRestriction(“orderDescription”,like “%h%”
abc));
Query query=session.createQuery(“from com.lara.Order”);
List<Order> list = query.list();
For(Order order : list)
{
System.out.println(order.getOrderId());
System.out.println(order.getOrderName());
System.out.println(order.getOrderDate());
System.out.println(order.getOrderDescription());
System.out.println(order.getOrderPrice());
System.out.println(order.getOrderBy());
}

*/
}

Now start the database (i.e Oracle) and run the program.

 when your sessionFactory object is createdthen only the table schema


is creating/generating.
 Immaterial of calling configure by java program/xml file by the time
of sessionFactory object creation time all the database related schemas
are generating.

Lara Technologies 080-41310124 90


http://javaeasytoall.com

 Eventhough you triggered 4 times the update query on the same


transaction only once is updates the query before commited.by this we
can save the network traffic.
 For the same transaction one object is keep on changing,it is calling
updateQuery before commiting.
 While in the case of save(), it is keep on calling/storing in the
database.where as in the case of saveOrUpdate(),it is storing the
object state in the cachi and it is called as first-level cachi.
 First-level-cachi is limited to transaction (when ever transaction is
goingto commit then cachi is called.)
 It is possible to keep more than one transaction in the same session.
 In one transaction we can keep as many database transactions as we
wish. Cachi is not available for the other transactions which is limited
to one transaction.
 First-level-cahi is automatic one.

Polymorphic mappings:

They are three types of polymorphi


c mappings.
1. One table per class hierarchy.
2. One table per subclass.
3. One table per concrete class.

1) One table per class hierarchy:


In this we will not create table for every Pojoclass we will
create table only for super class and all sub class attributes will present in the
same table.

hibernate.cfg.xml

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>

Lara Technologies 080-41310124 91


http://javaeasytoall.com

<!-- Database connection settings -->


<property
name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost/lara</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property
name="cache.provider_class">org.hibernate.cache.NoCacheProvider</prope
rty>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


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

<mapping resource="com/lara/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Person.java

package com.lara;

public class Person


{

Lara Technologies 080-41310124 92


http://javaeasytoall.com

private int id;


private String firstName;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}

Employee.java

package com.lara;

public class Employee extends Person


{
private String empNo;

public String getEmpNo() {


return empNo;
}

public void setEmpNo(String empNo) {


this.empNo = empNo;
}
}

PermanentEmployee.java

package com.lara;

public class PermanentEmployee extends Employee


{

Lara Technologies 080-41310124 93


http://javaeasytoall.com

private Double allowances;

public Double getAllowances() {


return allowances;
}

public void setAllowances(Double allowances) {


this.allowances = allowances;
}

Person.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 package="com.lara">

<class name="Person" table="PERSONS" discriminator-value=”p”>


<id name="id" column="PERSON_ID">
<generator class="native"/>
</id>
<property name="firstName" column="PERSON_FIRST_NAME"/>
<discriminator column=”P_TYPE” type=”string”/>
<subclass name="Employee" discriminator-value="e">
<property name="empNo" column="EMP_NO"/>
</subclass>
<subclass name="PermanentEmployee" discriminator-value="pe">
<property name="allowances" column="ALLOWANCES"/>
<subclass>
</class>
</hibernate-mapping>

Manager.java

package com.lara;

Lara Technologies 080-41310124 94


http://javaeasytoall.com

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

public class Manager


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

PermanentEmployee pe = new PermanentEmployee();


pe.setId(1);
pe.setAllowances(50000.00);

Configuration config = new Configuration();


config.configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(pe);
session.getTransaction().commit();
session.flush();
session.close();
}
}

2) One table per subclass:

For every subclass there is one table


In above example just change the Person.hbm.xml

Person.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 package="com.lara">

Lara Technologies 080-41310124 95


http://javaeasytoall.com

<class name="Person" table="PERSONS">


<id name="id" column="PERSON_ID">
<generator class="native"/>
</id>
<property name="firstName" column="PERSON_FIRST_NAME"/>
<joined-subclass name="Employee" table="P_E">
<key column="id"/>
<property name="empNo" column="EMP_NO"/>
</joined-subclass>
<joined-subclass name="PermanentEmployee" table="P_PE">
<key column="id"/>
<property name="allowances"
column="PERMANENTEMP_ALLOWANCES"/>
</joined-subclass>
</class>
</hibernate-mapping>

3)One table per concrete class:

In this develop table for every pojo class as we used earlier.

Example for Query interface:

hibernate.cfg.xml

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property
name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost/lara</property>
<property name="connection.username">root</property>

Lara Technologies 080-41310124 96


http://javaeasytoall.com

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

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property
name="cache.provider_class">org.hibernate.cache.NoCacheProvider</prope
rty>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


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

<mapping resource="com/lara/Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Person.java

package com.lara;
public class Person
{
private String id;

Lara Technologies 080-41310124 97


http://javaeasytoall.com

private String firstName;


private String lastName;
private Integer personAge;

public String getId() {


return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getPersonAge() {
return personAge;
}
public void setPersonAge(Integer personAge) {
this.personAge = personAge;
}
}

Person.hbm.xml

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

<hibernate-mapping>

<class name="com.lara.Person" table="PERSONS">

Lara Technologies 080-41310124 98


http://javaeasytoall.com

<id name="id" column="PERSON_ID">


<generator class="assigned"/>
</id>
<property name="firstName" column="PERSON_FIRST_NAME"/>
<property name="lastName" column="PERSON_LAST_NAME"/>
<property name="personAge" column="PERSON_AGE"/>
</class>

</hibernate-mapping>

Manager.java

package com.lara;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Manager{
public static void main(String[] args)
{
/*
Person p1 = new Person();

p1.setId("INDEX104");
p1.setFirstName("MANI");
p1.setLastName("KANTA");
p1.setPersonAge(23);
*/
Configuration config = new Configuration();
config.configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();

Query query = session.createQuery("from com.lara.Person");


List<Person> list = query.list();
for(Person p:list)
{

Lara Technologies 080-41310124 99


http://javaeasytoall.com

System.out.println(p.getId()+":"+p.getFirstName()
+":"+p.getPersonAge());
}
//session.save(p1);
session.getTransaction().commit();
session.flush();
session.close();
}
}

How to make composite primaryKey:

If we want to make two attributes as primary key field then create separate
class for two attributes and that class should implement Serialization and
override equals() and hashCode().

EG:
hibernate.cfg.xml

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


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

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->


<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">great123</property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

Lara Technologies 080-41310124 100


http://javaeasytoall.com

<!-- SQL dialect -->


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

<!-- Enable Hibernate's automatic session context management -->


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

<!-- Disable the second-level cache -->


<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


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

<!-- Drop and re-create the database schema on startup -->


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

<mapping resource="com/lara/Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Person.java

package com.lara;
public class Person
{
private PKField pkField;;
private String lastName;
private Integer personAge;

public PKField getPkField() {


return pkField;
}
public void setPkField(PKField pkField) {
this.pkField = pkField;
}

Lara Technologies 080-41310124 101


http://javaeasytoall.com

public String getLastName() {


return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getPersonAge() {
return personAge;
}
public void setPersonAge(Integer personAge) {
this.personAge = personAge;
}
}

PKField.java

package com.lara;

import java.io.Serializable;

public class PKField implements Serializable


{
private String id;
private String firstName;

public String getId() {


return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public boolean equals(Object obj)
{

Lara Technologies 080-41310124 102


http://javaeasytoall.com

PKField pk = (PKField)obj;
return id.equals(pk.id)&& firstName.equals(pk.firstName);
}
public int hashCode()
{
return id.hashCode()+firstName.hashCode();
}

Person.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 package="com.lara">

<class name="Person" table="PERSONS">


<composite-id name="pkField">
<key-property name="id" column="PERSON_ID"/>
<key-property name="firstName"
column="PERSON_FIRST_NAME"/>
</composite-id>
<property name="lastName" column="PERSON_LAST_NAME"/>
<property name="personAge" column="PERSON_AGE"/>
</class>
</hibernate-mapping>

Manager.java

package com.lara;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

Lara Technologies 080-41310124 103


http://javaeasytoall.com

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Manager


{
public static void main(String[] args)
{
/*

Person p1 = new Person();


PKField pk = new PKField();
pk.setId("INDEX102");
pk.setFirstName("MANI");
p1.setPkField(pk);
p1.setLastName("CHOUDHARY");
p1.setPersonAge(29);
*/

Configuration config = new Configuration();


config.configure();

SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();

session.beginTransaction();

String hql = "form com.lara.Person p where p.age=?";


Query query = session.createQuery(hql);
query.setString(0, "29");

Iterator<Person> it = query.iterate();
while(it.hasNext())
{
Person p = it.next();
System.out.println(p.getPkField().getFirstName());
}

//session.save(p1);

Lara Technologies 080-41310124 104


http://javaeasytoall.com

session.getTransaction().commit();

session.flush();
session.close();
/*
// To read a record
PKField pk1 = new PKField();
Pk.setId (101);
Pk.setFirstName(“abc”);
Person p2= (Person)session.load(com.lara.Person.class,pk1);
System.out.println(p2.getLastName());
System.out.println(p2.getPersonAge());
System.out.println(p2. PKField ().getId());
System.out.println(p2. PKField ().getFirstName());

*/

/*
// To get all records
List<Person> list=session.createCriteria
(com.lara.Person.class, list)
For(Person p1 : list)
{
System.out.println(p2.getLastName());
System.out.println(p2.getPersonAge());
System.out.println(p2. PKField ().getId());
System.out.println(p2. PKField ().getFirstName());
}

*/

/*
// To update one record
PKField pk1 = new PKField();
Pk.setId (101);
Pk.setFirstName(“abc”);

Lara Technologies 080-41310124 105


http://javaeasytoall.com

Person p2=(Person)session.load(com.lara.Person.class, 1);


P2.setFirstName(“LARA”);
P2.setAge(6);
P2.setLastName(“Tecnologies”);

Session.saveOrUpdate(p2);

*/

/*
// To delete one record

PKField pk1 = new PKField();


Pk.setId (101);
Pk.setFirstName(“abc”);

Person p2=(Person)session.load(com.lara.Person.class, 1);


P2.setFirstName(“LARA”);
P2.setAge(6);
P2.setLastName(“Tecnologies”);

Session.delete(p2);

*/

Lara Technologies 080-41310124 106


http://javaeasytoall.com

Java Annotations

The objective of changing older JDK versions to JDK5 largely


centered on enhancing ease-of-development. In other
words, the new features shift the responsibility for writing
the boilerplate code from the programmer to the compiler. If
the source code is boilerplate free, it becomes easier to
maintain. The resulting codes are also less likely to be bug-
prone. One of these new ease-of-development features in
JDK5 are annotations. Annotations are like meta-tags that
you can add to your code and apply them to package
declarations, type declarations, constructors, methods,
fields, parameters, and variables. As a result, you will have
helpful ways to indicate whether your methods are
dependent on other methods, whether they are incomplete,
whether your classes have references to other classes, and
so on.

Annotation-based development is certainly one of the latest


Java development trends. Annotation-based development
relieves Java developers from the pain of cumbersome
configuration. Quoting from Sun's official site, "It
(annotation-based development) lets us avoid writing
boilerplate code under many circumstances by enabling tools
to generate it from annotations in the source code. This
leads to a declarative programming style where the
programmer says what should be done and tools emit the
code to do it." Simply speaking, annotation is a mechanism
for associating a meta-tag with program elements and
allowing the compiler or the VM to extract program
behaviors from these annotated elements and generate
interdependent codes when necessary. In the first part of
this three-article series, I'll describe some basics of
annotation, their benefits, as well as some example usages.

The Basics

Lara Technologies 080-41310124 107


http://javaeasytoall.com

There are two things you need to consider with annotations.


One is the "annotation" itself; another is the "annotation
type." An annotation is the meta-tag that you will use in
your code to give it some life. Annotation type is used for
defining an annotation. You will use it when you want to
create your own custom annotation. The type is the actual
construct used, and the annotation is the specific usage of
that type.

An annotation type definition takes an "at" (@) sign,


followed by the interface keyword plus the annotation name.
On the other hand, an annotation takes the form of an "at"
sign (@), followed by the annotation type. This is simplest
form of annotation. Additionally, you can put data within
parenthesis after the annotation name. An example of each
can be seen below:

Example to Define an Annotation (Annotation type)


public @interface MyAnnotation {
String doSomething();
}

Example to Annotate Your Code (Annotation)


MyAnnotation (doSomething="What to do")
public void mymethod() {
....
}

Annotation Types

There are three annotation types:

 Marker: Marker type annotations have no elements,


except the annotation name itself.

Example:

public @interface MyAnnotation {


}

Lara Technologies 080-41310124 108


http://javaeasytoall.com

Usage:

@MyAnnotation
public void mymethod() {
....
}
 Single-Element: Single-element, or single-value type,
annotations provide a single piece of data only. This
can be represented with a data=value pair or, simply
with the value (a shortcut syntax) only, within
parenthesis.

Example:

public @interface MyAnnotation


{
String doSomething();
}

Usage:

@MyAnnotation ("What to do")


public void mymethod() {
....
}
 Full-value or multi-value: Full-value type
annotations have multiple data members. Therefore,
you must use a full data=value parameter syntax for
each member.

Example:

public @interface MyAnnotation {


String doSomething();
int count; String date();
}

Usage:

Lara Technologies 080-41310124 109


http://javaeasytoall.com

@MyAnnotation (doSomething="What to do",


count=1,
date="09-09-2005")
public void mymethod() {
....
}

Rules of Thumb for Defining Annotation Type

Here are some rules-of-thumb when defining an annotation


type:

1. Annotation declaration should start with an 'at' sign like


@, following with an interface keyword, following with
the annotation name.
2. Method declarations should not have any parameters.
3. Method declarations should not have any throws
clauses.
4. Return types of the method should be one of the
following:
o primitives
o String
o Class
o enum
o array of the above types

Annotations

There are two types of annotations available with JDK5:

 Simple annotations: These are the basic types


supplied with Tiger, which you can use to annotate your
code only; you cannot use those to create a custom
annotation type.
 Meta annotations: These are the annotation types
designed for annotating annotation-type declarations.
Simply speaking, these are called the annotations-of-
annotations.

Lara Technologies 080-41310124 110


http://javaeasytoall.com

Simple Annotations

There are only three types of simple annotations provided by


JDK5. They are:

 Override
 Deprecated
 Suppresswarnings

It's important to note that JDK5 (in other words, Tiger)


actually does not have many built-in annotations; rather, it
allows core Java the ability to support the annotation
feature. The charter for JSR-175 strictly dictated it was to
define a metadata facility. It was left to the programmers to
write custom annotation types and to other JSRs to write a
set of standard annotation types. The following sections will
describe each simple annotation in more depth, along with
examples.

The Override annotation

An override annotation indicates that the annotated method


is required to override a method in a super class. If a
method with this annotation does not override its super-
class's method, the compiler will generate an error. Example
1 demonstrates the override annotation:

Example 1
public class Test_Override {
@Override
public String toString() {
return super.toString() +
" Testing annotation name: 'Override'";
}
}

Lara Technologies 080-41310124 111


http://javaeasytoall.com

What happens if a spelling mistake occurs with the method


name? For example, if you change the name of the toString
method to "tostring" and compile the code, you will get
something like the following:

Compiling 1 source file to D:tempNew Folder (2)

TestJavaApplication1buildclasses
D:tempNew Folder (2)TestJavaApplication1srctest
myannotationTest_Override.java:24: method does
not override
a method from its superclass
@Override
1 error
BUILD FAILED (total time: 0 seconds)

The Deprecated annotation

This annotation indicates that when a deprecated program


element is used, the compiler should warn you about it.
Example 2 shows you the deprecated annotation.

Example 2

First, create a class with the deprecated method as follows:

public class Test_Deprecated {


@Deprecated
public void doSomething() {
System.out.println("Testing annotation name:
'Deprecated'");
}
}

Next, try to invoke this method from another class:

public class TestAnnotations {


public static void main(String arg[]) throws
Exception {
new TestAnnotations();
}

Lara Technologies 080-41310124 112


http://javaeasytoall.com

public TestAnnotations() {
Test_Deprecated t2=new Test_Deprecated();
t2.doSomething();
}

The doSomething() method in this example is declared as a


deprecated method. Therefore, this method should not be
used when this class is instantiated by other classes. If you
compile Test_Deprecated.java, no warning messages will be
generated by the compiler. But, if you try to compile
TestAnnotations.java where the deprecated method is used,
you will see something like this:

Compiling 1 source file to D:tempNew Folder


(2)TestJavaApplication1buildclasses
D:tempNew Folder
(2)TestJavaApplication1srctestmyannotation
TestAnnotations.java:27:
warning: [deprecation] doSomething() in
test.myannotation.Test_Deprecated has been
deprecated
t2.doSomething();
1 warning

The Suppresswarnings annotation

This annotation indicates that compiler warnings should be


shielded in the annotated element and all of its sub-
elements. The set of warnings suppressed in an element is
the superset of the warnings in all of its containing sub-
elements. As an example, if you annotate a class to
suppress one warning and one of its methods to suppress
another warning, both warnings will be suppressed at the
method level only. See Example 3 for the suppresswarnings
annotation.

Example 3
public class TestAnnotations {
public static void main(String arg[]) throws
Exception {

Lara Technologies 080-41310124 113


http://javaeasytoall.com

new TestAnnotations().doSomeTestNow();
}
@SuppressWarnings({"deprecation"})
public void doSomeTestNow() {
Test_Deprecated t2 = new Test_Deprecated();
t2.doSomething();
}
}

In this example, you are suppressing the deprecation


warning for the method listing shown in Example 2. Because
the method is suppressed, you are unlikely to view the
"deprecation" warning any more.

Note: It is a good idea to use this annotation at the most


deeply nested element where it is effective. Therefore, if you
want to suppress a warning in a particular method, you
should annotate that method rather than its class.

Meta-Annotations (Annotation Types)

Meta-annotations, which are actually known as the


annotations of annotations, contain four types. These are:

 Target
 Retention
 Documented
 Inherited

The Target annotation

The target annotation indicates the targeted elements of a


class in which the annotation type will be applicable. It
contains the following enumerated types as its value:

 @Target(ElementType.TYPE)—can be applied to any


element of a class
 @Target(ElementType.FIELD)—can be applied to a
field or property

Lara Technologies 080-41310124 114


http://javaeasytoall.com

 @Target(ElementType.METHOD)—can be applied to a
method level annotation
 @Target(ElementType.PARAMETER)—can be applied to
the parameters of a method
 @Target(ElementType.CONSTRUCTOR)—can be applied
to constructors
 @Target(ElementType.LOCAL_VARIABLE)—can be
applied to local variables
 @Target(ElementType.ANNOTATION_TYPE)—indicates
that the declared type itself is an annotation type

Example 4 demonstrates the target annotation:

Example 4

First, define an annotation named Test_Target with @Target


metadata, as follows:

@Target(ElementType.METHOD)
public @interface Test_Target {
public String doTestTarget();
}

Next, create a class that will use the Test_Target


annotation:

public class TestAnnotations {


public static void main(String arg[]) {
new TestAnnotations().doTestTarget();
}
@Test_Target(doTestTarget="Hello World !")
public void doTestTarget() {
System.out.printf("Testing Target
annotation");
}
}

The @Target(ElementType.METHOD) indicates that this


annotation type can be used to annotate only at the method

Lara Technologies 080-41310124 115


http://javaeasytoall.com

levels. If you compile the preceding code, no warning


messages will be shown. Now, if you declare a String
variable and apply your newly created annotation, what will
happen? Let me demonstrate this as follows:

public class TestAnnotations {


@Test_Target(doTestTarget="Hello World !")
private String str;
public static void main(String arg[]) {
new TestAnnotations().doTestTarget();
}
public void doTestTarget() {
System.out.printf("Testing Target
annotation");
}
}

The only change you can see from above is that the
annotation declaration is shifted from method-level to field-
level, which is not correct. Because you have defined your
annotation @Test_Target to be applicable only at method-
level, if you try to compile this class, you are likely to get
something like this:

"TestAnnotations.java":
D:R_AND_DTestAnnotationsrctestmyannotation
TestAnnotations.java:16:
annotation type not applicable to this kind of
declaration at line
16, column 0
@Test_Target(doTestTarget="Hello World !")
^
Error in javac compilation

The Retention annotation

The retention annotation indicates where and how long


annotations with this type are to be retained. There are
three values:

Lara Technologies 080-41310124 116


http://javaeasytoall.com

 RetentionPolicy.SOURCE—Annotations with this type


will be by retained only at the source level and will be
ignored by the compiler
 RetentionPolicy.CLASS—Annotations with this type
will be by retained by the compiler at compile time, but
will be ignored by the VM
 RetentionPolicy.RUNTIME—Annotations with this
type will be retained by the VM so they can be read
only at run-time

Example 5 shows you the RetentionPolicy.RUNTIME value in


action:

Example 5
@Retention(RetentionPolicy.RUNTIME)
public @interface Test_Retention {
String doTestRetention();
}

In this example, the @Retention(RetentionPolicy.RUNTIME)


annotation indicates that your Test_Retention annotation is
to be retained by the VM so that it can be read reflectively at
run-time.

The Documented annotation

The documented annotation indicates that an annotation


with this type should be documented by the javadoc tool. By
default, annotations are not included in javadoc. But if
@Documented is used, it then will be processed by javadoc-
like tools and the annotation type information will also be
included in the generated document. Example 6
demonstrates using @Documented further:

Example 6
@Documented
public @interface Test_Documented {
String doTestDocument();
}

Lara Technologies 080-41310124 117


http://javaeasytoall.com

Next, update your TestAnnotations class as follows:

public class TestAnnotations {


public static void main(String arg[]) {
new TestAnnotations().doSomeTestRetention();
new TestAnnotations().doSomeTestDocumented();
}
@Test_Retention (doTestRetention="Hello
retention test")
public void doSomeTestRetention() {
System.out.printf("Testing annotation
'Retention'");
}
@Test_Documented(doTestDocument="Hello
document")
public void doSomeTestDocumented() {
System.out.printf("Testing annotation
'Documented'");
}
}

Now, if you run the javadoc command and view the


generated TestAnnotations.html file, you will see something
like Figure 1.

Lara Technologies 080-41310124 118


http://javaeasytoall.com

Figure 1

As you can see from the screenshot, there is no annotation-


type information for the doSomeTestRetention() method.
But, this description is provided for the
doSomeTestDocumented() method. This is because of the
@Documented tag attached with your Test_Documented
annotation. Your earlier annotation Test_Retention did not
include this tag.

The Inherited annotation

This is a bit of a complex annotation type. It indicates that


the annotated class with this type is automatically inherited.
More specifically, if you define an annotation with the

Lara Technologies 080-41310124 119


http://javaeasytoall.com

@Inherited tag, then annotate a class with your annotation,


and finally extend the class in a subclass, all properties of
the parent class will be inherited into its subclass. With
Example 7, you will get an idea about the benefits of using
the @Inherited tag.

Example 7

First, define your annotation:

@Inherited
public @interface myParentObject {
boolean isInherited() default true;
String doSomething() default "Do what?";
}

Next, annotate a class with your annotation:

@myParentObject
public Class myChildObject {
}

As you can see, you do not have to define the interface


methods inside the implementing class. These are
automatically inherited because of using the @Inherited tag.
What would happen if you define the implementing class in
old-fashioned Java-style? Take a look at this—defining the
implementation class in an old-style-java way:

public class myChildObject implements


myParentObject {
public boolean isInherited() {
return false;
}
public String doSomething() {
return "";
}
public boolean equals(Object obj) {
return false;
}

Lara Technologies 080-41310124 120


http://javaeasytoall.com

public int hashCode() {


return 0;
}
public String toString() {
return "";
}
public Class annotationType() {
return null;
}
}

Do you see the difference? You can see that you will have to
implement all the methods that the parent interface owns.
Besides the isInherited() and doSomething() methods from
myParentObject, you will have to implement the equals(),
toString(), and hasCode() methods of java.lang.Object and
also the annotationType() method of
java.lang.annotation.Annotation class. It does not matter
whether you want to implement these methods or not; you
will have to include these in your inherited object.

Lara Technologies 080-41310124 121


http://javaeasytoall.com

Using Annotations in Hibernate:

Annotation is for providing meta information. It is introduced in jdk5.0.


Annotations provide data about a program that is not part of the program
itself.they have no direct effect on the operation of the annotate.

There are 2 things u need to consider with annotations they are:

1. annotation: the mega data that u will use in ur code to give it some
life. It is specific usage of that type.
2. annotation-type: is used for defining an annotation. It is actual
construct used.

There are three types of Annotations they are:

1. Marker: this type have no elements,except the annotation name itself.

2. Single-Element: provides a single piece of data only. This can be


represented with a data=value pair or, simply with the value only
within the peranthasis.

3. Full-value or Multi-value: it is having multiple data members. we


must use a full data=value parameter systax for each member.

Uses of Annotations are:

1. Information for the compiler: Annotations can be used by the


compiler to delete errors or supress warnings.

2. Compiler-time and deployment-time processing: Software tools can


process annotation information to generate code ,XML files and so on.

3. Run-time prucessing: sone Annotations are available to be examined


at runtime.

Annotations can be applied to a program’s declarations of a classes,fields,


methods and other elements.

The Annotation appears first, often on its own line, and may include
elements with named or unnamed values.

Lara Technologies 080-41310124 122


http://javaeasytoall.com

Instead of writing hbm file we can keep that information, we can write
through anotations.it will act as a member as like class,interface, enum
etc.anotations mainly to give.

Annotation is also getting a .class file as like class,interface.

we can use Annotations instead of providing documentation and comments.

The rules for developing an annotation:


1. annotation contains only method definitions.
2. methods should not take any parameter and should not throw any
exceptional class.
3. return type of method declaration should be primitive or String or
class or ennum or array of the above types but should not be void.
4. annotation can be used for classes/packages/methods.
5. through target we can able to fix to classes/packages/methods.
6. if target is type, we can fix annatations to classes/interface/methods.
7. if target is field, we can fix annatations to classes/interface/methods

.Examle:

Public class Test


{
@Override
Public String tostring()
{
Return string;
}
}

@Override: indicates that annotation which provides meta information to


that tostring(). It is overriden method it is not your own method

@Target: Annotations can be used in any of the place by defining target.


Need to fix the target to where to use that
Example:@target(ElementType.type/method/parameter …etc.)

@Depricated: we can supress the depricated methods.

Lara Technologies 080-41310124 123


http://javaeasytoall.com

@SuppressWarnigs: To tell explicitly to the compiler


Example: @supressWarnings({“depricated”})

@Retention: Whether this annotation want to display for particular class or


for particular JVM then it is limited to that not for the otjers.
Exaple: @retention(RetentionPolicy.class/runtime/source/… etc.)

@Documented: when ever you are using this annotation that .java file java
documentation method is available.(it also should be documented.)

To use annotation for providing mapping information without hbm file in the
hibernate. To avoid mapping resource inside hibernate-mapping tag.
For that update the buildpath with 4 types of JAR files they are:

1. hibernate-3.2.3.jar and dependent jar files.


2. Oracle 4th type Driver JAR file
3. sringframework-2.0.4 with dependencies(relavent JAR files).
4. ejb3.0-persistance.jar(must and should)

examlpe1:

class A
{
@diprecated
String test()
{
System,out,println(“Dipricated method.”);
}
}

Class Manager
{
Public static void main(String args[])
{
A a1=new A();
A1.test();

Lara Technologies 080-41310124 124


http://javaeasytoall.com

Examle2:

Class Test
{
@suppresswarnings(“unchecked”)
Public static void main(String args[])
{
ArrayList list=new ArrayList();
List.add(10);
}
}

Developing our own Annotation:

public @interface HelloAnnotation


{
String hello();
}

class A
{
@HelloAnnotation(hello=”welcome to all.”)
}

class B extends A
{

public @interface TestAnnotation


{
int count();
String date();
}
class Test

Lara Technologies 080-41310124 125


http://javaeasytoall.com

{
@TestAnnotation(count=100, date=02-02-2009)
}
Example: hibernate programe with usage of annotations.

import javax.persistance.column;
import javax.persistance.entity;
import javax.persistance.Id;
import javax.persistance.jable;

@Entity
@Table(name=”Person”)

public class Person


{
@Id
@column(name=”person_id”)

private int personId;

@column(name=”person_name”)
privateString personName;

public int getPersonId() {


return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}

package com.lara;

Lara Technologies 080-41310124 126


http://javaeasytoall.com

public class Manager


{
Public static void main(String args[])
{
Person p1=new person();
P1.setPersonId(1010);
P1.setPersonName(“UDAY ”);

AnotationConfiguration ac=new AnotationConfiguration();


ac.configure();
sessionFactory sf=ac.buildSessionFactory();
Session session=sf.openSession();

Session.beginTransaction();

Session.save(p1);

Session.getTransaction.commit();

Session.flush();
Session.close();
}
}

Lara Technologies 080-41310124 127


http://javaeasytoall.com

CacheManagement:

In hibernate we can achieve two types of cache:


1. FirstLevel cache.
2. SecondLevel cache.

Cache means storing data inside a memory and avoiding lenghy


accessing for frequent used data.

1) FirstLevel cache:

For this we dont need to set explicitly. By default we will get this cache
It store the persistant object in the session object.
It is available for only one user.
Inorder to manage this, use the methods which are there inside session
object.
Some methods are
1. evict(Object): It is used to remove a particular Object.
2. clear(): To remove all the objects.

2) SecondLevel cache:
We will not get this cache implcitly. We have to set explicitly.
It stores the persintant objects inside a SessionFactory.
It is available for all the users in the same application.
Threre are several open source technics for achieving this cache.
1. EHCache.
2. OpenSymphony OSCache.
3. SwarnCache.
4. JbossCache.
Hibernate supports all above mentoned open source cache technics.
We have to set explicitly in the config file by mentioning the cache
technic type.
Cache technic type can be mentioned by choosing a suitable class from a
package org.hibernate.cache

To set 2nd level cache,


Open hibernate.cfg,xml
<property name="cache.provider_class">
org.hibernate.cache.EHCache
</property>

Lara Technologies 080-41310124 128


http://javaeasytoall.com

Persistent objects :

Short-lived, single threaded objects containing persistent state and


business function. These might be ordinary JavaBeans/POJOs, the
only special thing about them is that they are currently associated with
(exactly one) Session. As soon as the Session is closed, they will be
detached and free to use in any application layer (e.g. directly as data
transfer objects to and from presentation).

Lara Technologies 080-41310124 129


http://javaeasytoall.com

FAQS

Faqs

1) What is ORM?

ORM stands for Object Relational Mapping. It’s a programmed and


translucent perseverance of objects in Java application into the database
tables using the metadata that defines the mapping between the objects and
the database. It works by transferring the data from one representation into
another.

ORM is Object Relational Mapping which transforms objects in Java,


which is based on O-O principle, into the table of databases and for this
reads the metadata which has all the mappings of objects and tables in
database.

2) What is a pure relational ORM?

The entire application, including the user interface, is designed around the
relational model and SQL-based relational operations.

3) What does an ORM solution comprises of?

It should have an API for performing basic CRUD (Create, Read, Update,
Delete) operations on objects of persistent classes

Should have a language or an API for specifying queries that refer to the
classes and the properties of classes

An ability for specifying mapping metadata

It should have a technique for ORM implementation to interact with


transactional objects to perform dirty checking, lazy association fetching,
and other optimization functions

4). What are different levels of ORM quality?

There are 4 levels defined for ORM quality

Lara Technologies 080-41310124 130


http://javaeasytoall.com

i. Pure relational:

The entire application, including the UI is designed around the


relational model and SQL based relational operation.

ii. Light Object Mapping:

The entities are represented as classes that are mapped


manually to the relational tables. The code is hidden from the
business logic using specific design patterns. This approach is
successful for applications with a less number of entities, or
applications with common, metadata-driven data models. This
approach is most known to all.

iii. Medium Object Mapping:

The application is designed around an object model. The SQL


code is generated at build time. And the association between
objects is supported by the persistence mechanism, and queries
are specified using an object-oriented expression language. This
is best suited for medium-sized applications with some complex
transactions. Used when the mapping exceed 25 different
database products at a time.

iv. Full Object Mapping

Full Object Mapping supports sophisticated object modeling: composition,


inheritance, polymorphism and persistence. The persistence layer
implements transparent persistence: persistent classes do not inherit any
special base class or have to implement or special interface. Efficient
fetching strategies and caching strategies are implemented transparently to
the application.

5) Why do you need ORM tools like hibernate?

Answer 1 The main advantage of ORM like hibernate is that it shields


developers from messy SQL. Apart from this, ORM provides following
benefits:

 Improved productivity

Lara Technologies 080-41310124 131


http://javaeasytoall.com

High-level object-oriented API


o
o Less Java code to write
o No SQL to write
 Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
 Improved maintainability
o A lot less code to write
 Improved portability

ORM framework generates database-specific SQL for you

Answer 2 : There are many benefits from these. Out of which the
following are the most important one.

i. Productivity – Hibernate reduces the burden of developer by


providing much of the functionality and let the developer to
concentrate on business logic.
ii. Maintainability – As hibernate provides most of the
functionality, the LOC for the application will be reduced and it
is easy to maintain. By automated object/relational persistence
it even reduces the LOC.

iii. Performance – Hand-coded persistence provided greater


performance than automated one. But this is not true all the
times. But in hibernate, it provides more optimization that
works all the time there by increasing the performance. If it is
automated persistence then it still increases the performance.

iv. Vendor independence – Irrespective of the different types of


databases that are there, hibernate provides a much easier way
to develop a cross platform application.

6) What is Hibernate?

Hibernate is powerful, high performance object/relational persistence and


query service. Hibernate lets developers develop persistent class following

Lara Technologies 080-41310124 132


http://javaeasytoall.com

object-oriented principles such as association, inheritance, polymorphism,


composition and collections.

Hibernate is pure Java object-oriented mapping(ORM) and persistence


framework that allows you to map plain old Java objects to relational
database tables using XML configuration files. Its purpose is to relieve the
developer from a significant amount of relational data persistence-related
programming tasks.

7) What are the benefits of ORM and Hibernate?

 Productivity: Hibernate provides much of the functionality, so


developers focuses on business logic
 Maintainability: LOC is very less
 Performance: Automated persistence works fast
 Vendor Independence: Easier for cross platform, does not depend on
any database.

8) What are the best practices for Hibernate?

1. Use JavaBeans

2. Implement equals() and hashCode(), but don’t use id if the id field is


surrogate key

3. Implement serializable interface, useful when migrating to multi-


processor cluster.

4. Persistence class should not be final.

Lara Technologies 080-41310124 133


http://javaeasytoall.com

9) Show Hibernate overview?

10) What are the advantages of Hibernate over jdbc?

Hibernate Vs. JDBC :-

JDBC Hibernate
With JDBC, developer has to write Hibernate is flexible and powerful
code to map an object model's data ORM solution to map Java classes to

Lara Technologies 080-41310124 134


http://javaeasytoall.com

database tables. Hibernate itself takes


representation to a relational data
care of this mapping using XML files
model and its corresponding database
so developer does not need to write
schema.
code for this.
Hibernate provides transparent
With JDBC, the automatic mapping
persistence and developer does not
of Java objects with database tables
need to write code explicitly to map
and vice versa conversion is to be
database tables tuples to application
taken care of by the developer
objects during interaction with
manually with lines of code.
RDBMS.
Hibernate provides a powerful query
language Hibernate Query Language
JDBC supports only native
(independent from type of database)
Structured Query Language (SQL).
that is expressed in a familiar SQL
Developer has to find out the
like syntax and includes full support
efficient way to access database, i.e.
for polymorphic queries. Hibernate
to select effective query from a
also supports native SQL statements.
number of queries to perform same
It also selects an effective way to
task.
perform a database manipulation task
for an application.
Application using JDBC to handle
persistent data (database tables)
having database specific code in
large amount. The code written to Hibernate provides this mapping
map table data to application objects itself. The actual mapping between
and vice versa is actually to map tables and application objects is done
table fields to object properties. As in XML files. If there is change in
table changed or database changed Database or in any table then the only
then it’s essential to change object need to change XML file properties.
structure as well as to change code
written to map table-to-object/object-
to-table.
With JDBC, it is developer’s Hibernate reduces lines of code by
responsibility to handle JDBC result maintaining object-table mapping
set and convert it to Java objects itself and returns result to application
through code to use this persistent in form of Java objects. It relieves
data in application. So with JDBC, programmer from manual handling of

Lara Technologies 080-41310124 135


http://javaeasytoall.com

persistent data, hence reducing the


mapping between Java objects and
development time and maintenance
database tables is done manually.
cost.
Hibernate, with Transparent
Persistence, cache is set to
application work space. Relational
tuples are moved to this cache as a
result of query. It improves
With JDBC, caching is maintained by
performance if client application
hand-coding.
reads same data many times for same
write. Automatic Transparent
Persistence allows the developer to
concentrate more on business logic
rather than this application code.
Hibernate enables developer to define
version type field to application, due
to this defined field Hibernate
updates version field of database
table every time relational tuple is
updated in form of Java class object
In JDBC there is no check that
to that table. So if two users retrieve
always every user has updated data.
same tuple and then modify it and
This check has to be added by the
one user save this modified tuple to
developer.
database, version is automatically
updated for this tuple by Hibernate.
When other user tries to save updated
tuple to database then it does not
allow saving it because this user does
not have updated data.

11)What are POJOs?

POJO stands for Plain Old Java Objects. These are just basic JavaBeans
that have defined setter and getter methods for all the properties that are
there in that bean. Besides they can also have some business logic related

Lara Technologies 080-41310124 136


http://javaeasytoall.com

to that property. Hibernate applications works efficiently with POJOs


rather then simple java classes.

12) What is object/relational mapping metadata?

ORM tools require a metadata format for the application to specify the
mapping between classes and tables, properties and columns, associations
and foreign keys, Java types and SQL types. This information is called
the object/relational mapping metadata. It defines the transformation
between the different data type systems and relationship representations.

13) What Does Hibernate Simplify?

Hibernate simplifies:

 Saving and retrieving your domain objects


 Making database column and table name changes
 Centralizing pre save and post retrieve logic
 Complex joins for retrieving related items

Schema creation from object model

14) What is the file extension you use for hibernate mapping file?

The name of the file should be like this : filename.hbm.xml


The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice
to follow this extension.

15) What is the need for Hibernate xml mapping file?

Hibernate mapping file tells Hibernate which tables and columns to use to
load and store objects. Typical mapping file look as follows:

Lara Technologies 080-41310124 137


http://javaeasytoall.com

16) What are the important tags of hibernate.cfg.xml?

An Action Class is an adapter between the contents of an incoming HTTP


rest and the corresponding business logic that should be executed to process
this rest.

17) What are different environments to configure hibernate?

Lara Technologies 080-41310124 138


http://javaeasytoall.com

There are mainly two types of environments in which the configuration


of hibernate application differs.

i. Managed environment – In this kind of environment everything


from database connections, transaction boundaries, security levels and
all are defined. An example of this kind of environment is
environment provided by application servers such as JBoss, Weblogic
and WebSphere.
ii. Non-managed environment – This kind of environment provides a
basic configuration template. Tomcat is one of the best examples that
provide this kind of environment.

18) How will you configure Hibernate?


The configuration files hibernate.cfg.xml (or hibernate.properties) and
mapping files *.hbm.xml are used by the Configuration class to create (i.e.
configure and bootstrap hibernate) the SessionFactory, which in turn creates
the Session instances. Session instances are the primary interface for the
persistence service.

• hibernate.cfg.xml (alternatively can use hibernate.properties): These two


files are used to configure the hibernate sevice (connection driver class,
connection URL, connection username, connection password, dialect etc). If
both files are present in the classpath then hibernate.cfg.xml file overrides
the settings found in the hibernate.properties file.

• Mapping files (*.hbm.xml): These files are used to map persistent objects
to a relational database. It is the best practice to store each object in an
individual mapping file (i.e mapping file per class) because storing large
number of persistent classes into one mapping file can be difficult to manage
and maintain. The naming convention is to use the same name as the
persistent (POJO) class name. For example Account.class will have a
mapping file named Account.hbm.xml. Alternatively hibernate annotations
can be used as part of your persistent class code instead of the *.hbm.xml
files.

19) What are the most common methods of Hibernate configuration?

Lara Technologies 080-41310124 139


http://javaeasytoall.com

The most common methods of Hibernate configuration are:

 Programmatic configuration

XML configuration (hibernate.cfg.xml)

20) What is meant by Method chaining?

Method chaining is a programming technique that is supported by many


hibernate interfaces. This is less readable when compared to actual java
code. And it is not mandatory to use this format. Look how a
SessionFactory is created when we use method chaining.
SessionFactory sessions = new Configuration()
.addResource("myinstance/MyConfig.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();

22) How do you map Java Objects with Database tables?


 First we need to write Java domain objects (beans with setter and
getter). The variables should be same as database columns.
 Write hbm.xml, where we map java class to table and database
columns to Java class variables.

Example :

<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>

23) What are the different methods of identifying an object?

Lara Technologies 080-41310124 140


http://javaeasytoall.com

There are three methods by which an object can be identified.

i. Object identity –Objects are identical if they reside in the same


memory location in the JVM. This can be checked by using the
= = operator.
ii. Object equality – Objects are equal if they have the same
value, as defined by the equals( ) method. Classes that don’t
explicitly override this method inherit the implementation
defined by java.lang.Object, which compares object identity.

iii. Database identity – Objects stored in a relational database are


identical if they represent the same row or, equivalently, share
the same table and primary key value.

24) What are the different types of property and class


mappings?

 Typical and most common property mapping

<property name="description" column="DESCRIPTION"


type="string"/>

Or

<property name="description" type="string">


<column name="DESCRIPTION"/>
</property>

 Derived properties

<property name="averageBidAmount" formula="( select


AVG(b.AMOUNT) from BID b where b.ITEM_ID = ITEM_ID )"
type="big_decimal"/>
 Typical and most common property mapping

Lara Technologies 080-41310124 141


http://javaeasytoall.com

<property name="description" column="DESCRIPTION"


type="string"/>
 Controlling inserts and updates

<property name="name" column="NAME" type="string"


insert="false" update="false"/>

25) What are Callback interfaces?

These interfaces are used in the application to receive a notification when


some object events occur. Like when an object is loaded, saved or
deleted. There is no need to implement callbacks in hibernate
applications, but they’re useful for implementing certain kinds of generic
functionality.

26) What are Extension interfaces?

When the built-in functionalities provided by hibernate is not sufficient


enough, it provides a way so that user can include other interfaces and
implement those interfaces for user desire functionality. These interfaces
are called as Extension interfaces.

27) What are the Extension interfaces that are there in


hibernate?

There are many extension interfaces provided by hibernate.

 ProxyFactory interface - used to create proxies


 ConnectionProvider interface – used for JDBC connection
management

 TransactionFactory interface – Used for transaction


management

 Transaction interface – Used for transaction management

 TransactionManagementLookup interface – Used in


transaction management.

Lara Technologies 080-41310124 142


http://javaeasytoall.com

 Cahce interface – provides caching techniques and strategies

 CacheProvider interface – same as Cache interface

 ClassPersister interface – provides ORM strategies

 IdentifierGenerator interface – used for primary key


generation

 Dialect abstract class – provides SQL support

28) What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the
most important one.

i. Session Interface – This is the primary interface used by


hibernate applications. The instances of this interface are
lightweight and are inexpensive to create and destroy. Hibernate
sessions are not thread safe.
ii. SessionFactory Interface – This is a factory that delivers the
session objects to hibernate application. Generally there will be
a single SessionFactory for the whole application and it will be
shared among all the application threads.

iii. Configuration Interface – This interface is used to configure


and bootstrap hibernate. The instance of this interface is used
by the application in order to specify the location of hibernate
specific mapping documents.

iv. Transaction Interface – This is an optional interface but the


above three interfaces are mandatory in each and every
application. This interface abstracts the code from any kind of
transaction implementations such as JDBC transaction, JTA
transaction.

v. Query and Criteria Interface – This interface allows the user


to perform queries and also control the flow of the query
execution.

29) what is SessionFactory?

Lara Technologies 080-41310124 143


http://javaeasytoall.com

SessionFactory is an interface from which the application gets Session


instances. SessionFactory caches generate SQL statements and other
mapping metadata that hibernate uses at runtime. Typically one instance of
SessionFactory at startup is created for the whole application.

30) How do you create a SessionFactory?

Configuration cfg = new Configuration();


cfg.addResource("myinstance/MyConfig.hbm.xml");
cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();

First, we need to create an instance of Configuration and use that instance to


refer to the location of the configuration file. After configuring this instance
is used to create the SessionFactory by calling the method
buildSessionFactory().

31) Is SessionFactory a thread safe object?

Yes, SessionFactory is a threadsafe, so many threads can request for session


and immutable cache of compiled mappings for a single database.

32) What is session?

Session is a lightweight and non thread safe object that represents a single-
unit-of-work with the database. Sessions are opened by SessionFactory and
closed when all the work is complete. It represents a persistence manager
that manages operations like storing and retrieving objects from database.
Instances of sessions are inexpensive to create and destroy.

A single-threaded, short-lived object representing a conversation between


the application and the persistent Store.

33) What role does the Session interface play in Hibernate?

The Session interface is the primary interface used by Hibernate


applications. It is a single-threaded, short-lived object representing a
conversation between the application and the persistent store. It allows you
to create query objects to retrieve persistent objects.

Lara Technologies 080-41310124 144


http://javaeasytoall.com

Session session = sessionFactory.openSession();

Session interface role:

 Wraps a JDBC connection


 Factory for Transaction
 Holds a mandatory (first-level) cache of persistent objects, used when
navigating the object graph or looking up objects by identifier

34) What role does the SessionFactory interface play in Hibernate?

The application obtains Session instances from a SessionFactory. There is


typically a single SessionFactory for the whole application—created during
application initialization. The SessionFactory caches generate SQL
statements and other mapping metadata that Hibernate uses at runtime. It
also holds cached data that has been read in one unit of work and may be
reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

35) What is configuration interface in hibernate?

The application uses the configuration interface to specify the location of


mapping documents and hibernate specific properties and then creates a
SessionFactory out of it.

36) What is the general flow of Hibernate communication with


RDBMS?

The general flow of Hibernate communication with RDBMS is :

 Load the Hibernate configuration file and create configuration object.


It will automatically load all hbm mapping files
 Create session factory from configuration object
 Get one session from this session factory
 Create HQL Query

Lara Technologies 080-41310124 145


http://javaeasytoall.com

Execute query to get list containing Java objects

37) How can Hibernate be configured to access an instance variable


directly and not through a setter method ?

By mapping the property with access="field" in Hibernate metadata. This


forces hibernate to bypass the setter method and access the instance
variable directly while initializing a newly loaded object.

38) What is transactional write-behind?

Hibernate uses a sophisticated algorithm to determine an efficient


ordering that avoids database foreign key constraint violations but is still
sufficiently predictable to the user. This feature is called transactional
write-behind.

39) How can a whole class be mapped as immutable?

Mark the class as mutable="false" (Default is true),. This specifies that


instances of the class are (not) mutable. Immutable classes, may not be
updated or deleted by the application.

40) What does hibernate.properties file consist of?

This is a property file that should be placed in application class path. So when the
Configuration object is created, hibernate is first initialized. At this moment the
application will automatically detect and read this hibernate.properties file.

hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class =
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class =
net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

41). What are detached objects, transient object, and persistent object?

Transient Objects:

Lara Technologies 080-41310124 146


http://javaeasytoall.com

Transient Objects are the objects or instances of persistent classes


that are not currently in session.

Detached Objects:

A detached object is an object that has been persistent but the session
is closed but still can be attached to another session and those objects can be
passed across layers all the way up to the presentation layer without having
to use any Data Transfer Objects.

Pros: Can be passed up to presentation layer without use of DTO’s

These detached objects get modified outside a transaction and later on


re attached to a new transaction through another session.

Cons: Working with detached objects is quite cumbersome and using Data
Transfer Object for the presentation layers
is better than using detached
objects.

Persistent Object:

Persistent Object is the object that is in session currently. It has a


representation in the database and an identifier value and might have been
saved or loaded.

42) How does Hibernate distinguish between transient and detached


objects?

Hibernate uses the version property if there exist one or uses identifier
value.

43) How do you switch between relational databases without code


changes?

Using Hibernate SQL Dialects , we can switch databases. Hibernate will


generate appropriate hql queries based on the dialect defined.

44) If you want to see the Hibernate generated SQL statements on


console, what should we do?

Lara Technologies 080-41310124 147


http://javaeasytoall.com

In Hibernate configuration file set as follows:


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

45) How do you define sequence generated primary key in hibernate?

Using <generator> tag.


Example:-

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


<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>

46) What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to
express queries in its own portable SQL extension and this is called as
HQL. It also allows the user to express in native SQL.

Answer 2 :

Hibernate offers a query language that embodies a very powerful and


flexible mechanism to query, store, update, and retrieve objects from a
database. This language, the Hibernate query Language (HQL), is an
object-oriented extension to SQL.

47) What are the ways to express joins in HQL?

HQL provides four ways of expressing (inner and outer) joins:-

 An implicit association join


 An ordinary join in the FROM clause
 A fetch join in the FROM clause.

A theta-style join in the WHERE clause.


48) Explain Criteria API

Lara Technologies 080-41310124 148


http://javaeasytoall.com

Criteria is a simplified API for retrieving entities by composing Criterion


objects. This is a very convenient approach for functionality like "search"
screens where there is a variable number of conditions to be placed upon the
result set.
Example :

List employees = session.createCriteria(Employee.class)


.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();
49) What do you mean by Named – SQL query?

Named SQL queries are defined in the mapping xml document and called
wherever required.
Example:

<sql-query name = "empdetails">


<return alias="emp" class="com.test.Employee"/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

Invoke Named Query :

List people = session.getNamedQuery("empdetails")


.setString("TomBrady", name)
.setMaxResults(50)
.list();

50) How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true">


<return alias="emp" class="employee">
<return-property name="empid" column="EMP_ID"/>

Lara Technologies 080-41310124 149


http://javaeasytoall.com

<return-property name="name" column="EMP_NAME"/>


<return-property name="address" column="EMP_ADDRESS"/>
{ ? = call selectAllEmployees() }
</return>
</sql-query>

51) What are the types of Hibernate instance states ?

Three types of instance states:

 Transient -The instance is not associated with any persistence context


 Persistent -The instance is associated with a persistence context

Detached -The instance was associated with a persistence context which


has been closed – currently not associated

52) What’s the difference between load() and get()?

load() vs. get() :-

load() get()
If you are not sure that the object
Only use the load() method if you are
exists, then use one of the get()
sure that the object exists.
methods.
load() method will throw an exception get() method will return null if the
if the unique id is not found in the unique id is not found in the
database. database.
load() just returns a proxy by default
get() will hit the database
and database won’t be hit until the
immediately.
proxy is first invoked.

53) What is the difference between and merge and update ?


Use update() if you are sure that the session does not contain an already
persistent instance with the same identifier, and merge() if you want to

Lara Technologies 080-41310124 150


http://javaeasytoall.com

merge your modifications at any time without consideration of the state of


the session

54) What are the Collection types in Hibernate ?


 Bag
 Set
 List
 Array

Map

55) What are managed associations and hibernate associations?

Associations that are related to container management persistence are called


managed associations. These are bi-directional associations. Coming to
hibernate associations, these are unidirectional.

56) Define cascade and inverse option in one-many mapping?

Cascade – enable operation to cascade to child entities.

Cascade = “all | none | save-update | delete | all-delete-orphan”

Inverse - mark this collection as the “inverse” end of a bidirectional


association.

Inverse=”true|false”

Essentially “inverse” indicates which end of a relationship should be


ignored, so when persisting a parent who has collection of children, should
you ask the parent for its list of children or ask the children who the parents
are?

57) What is the use of dynamic-insert and dynamic-update attributes in


a class mapping?

Criteria is a simplified API for retrieving entities by composing Criterion


objects. This is a very convenient approach for functionality like "search"

Lara Technologies 080-41310124 151


http://javaeasytoall.com

screens where there is a variable number of conditions to be placed upon the


result set.

 dynamic-update (defaults to false): Specifies that UPDATE SQL


should be generated at runtime and contain only those columns whose
values have changed

dynamic-insert (defaults to false): Specifies that INSERT SQL should be


generated at runtime and contain only the columns whose values are not
null.

58) What are derived properties?

The properties that are not mapped to a column, but calculated at runtime by
evaluation of an expression are called derived properties. The expression can
be defined using formula attribute of the element.

59) What is dirty checking?

Automatic dirty checking or dirty checking is a feature in hibernate that


saves the effort of explicitly asking Hibernate to update the database when
we modify the state of an object inside a transaction.

60) What do you mean by fetch strategy?

A fetching strategy is the strategy Hibernate will use for retrieving


associated objects if the application needs to navigate through the
association. Fetch strategies may be declared in the O/R mapping metadata,
or over-ridden by a particular HQL or Criteria Query.

61) What do you mean by lazy fetching?

It’s a fetching strategy used by Hibernate to constraint the retrieval of


associated objects when application just needs the objects and doesn’t need
to navigate the association.

62) What is table per subclass, table per class hierarchy and table per
concrete class

These all are inheritance mapping based

Lara Technologies 080-41310124 152


http://javaeasytoall.com

Table Per Subclass:

63) What is lazy initialization?

Book—–publisher

Many to one

If you retrieve book then publisher is also retrieved with it.

If you use getPublisher without closing the session then publisher is


accessible, but if we access publisher after session is closed then its an error.
This feature of Hibernate is called lazy initialization. This avoids
unnecessary database queries and enhances the performance.

64) What is unidirectional and bidirectional mapping?

If we want to get reference of child table or object while retrieving parent


table or object and not vice-versa, then this type of mapping done is called
unidirectional mapping.

If we want to get reference of child table or object while retrieving parent


table or child and also vice-versa, the this type of mapping done is called
bidirectional mapping.

65) Explain about collection mapping, association mapping, component


mapping, inheritance mapping?

Collection Mapping:

It’s a kind of mapping done in Hibernate to map a collection defined


in persistent java object. Basically we can use Bag, Set, List, Array, and Map
in collection mapping as defined in Java Objects. Hibernate basically
requires persistent collection-valued fields be declared as an interface type.

Association Mapping:

Lara Technologies 080-41310124 153


http://javaeasytoall.com

It’s a mapping done in Hibernate generally to show the relation


between persistent object. The different mapping often used is one-one, one-
many, many-one, many-many.

Component-mapping:

It’s a mapping done in Hibernate to map component (composition in


OOP) which is later persisted as value type and not entity type.

66) What is component mapping in Hibernate?


 A component is an object saved as a value, not as a reference
 A component can be saved directly without needing to declare
interfaces or identifier properties
 Required to define an empty constructor
 Shared references not supported

Example:

67) What is the difference between sorted and ordered collection in


hibernate?

Lara Technologies 080-41310124 154


http://javaeasytoall.com

sorted collection vs. order collection :-

sorted collection order collection


A sorted collection is sorting a
collection by utilizing the sorting
features provided by the Java Order collection is sorting a
collections framework. The sorting collection by specifying the order-by
occurs in the memory of JVM which clause for sorting this collection
running Hibernate, after the data when retrieval.
being read from database using java
comparator.
If your collection is not large, it will If your collection is very large, it will
be more efficient way to sort it. be more efficient way to sort it .

68) What is inheritance mapping strategy? (OR) What are the different
approaches to represent an inheritance hierarchy?

It’s a typical strategy to map “whole object graph” which are related to each
other through inheritance. We use these inheritance mapping strategies

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

69) What is table per subclass mapping?

It’s an inheritance mapping strategy in which we create table for each


subclasses in the inheritance hierarchy and map it according to that in our
mapping metadata.

70) What is table per class hierarchy?

It’s an inheritance mapping strategy in which a single table is created for all
classes in the inheritance hierarchy and map it accordingly in our mapping
file.

71) What is table per concrete class?

Lara Technologies 080-41310124 155


http://javaeasytoall.com

Its one of the inheritance mapping strategy in which we create table for each
concrete class and map it accordingly in our mapping file in Java side.
Disadvantage is that we could repeat the same properties in the concrete
classes, including inherited properties.

72) What are the differences between EJB 3.0 & Hibernate ?

Hibernate Vs EJB 3.0 :-

Hibernate EJB 3.0


Persistence Context-Set of entities
Session–Cache or collection of loaded
that can be managed by a given
objects relating to a single unit of
EntityManager is defined by a
work
persistence unit
Java 5.0 Annotations used to
XDoclet Annotations used to support
support Attribute Oriented
Attribute Oriented Programming
Programming
Defines HQL for expressing queries Defines EJB QL for expressing
to the database queries
Supports Entity Relationships
Support Entity Relationships
through mapping files and annotations
through Java 5.0 annotations
in JavaDoc
Provides a Persistence Manager Provides and Entity Manager
API exposed via the Session, Query, Interface for managing CRUD
Criteria, and Transaction API operations for an Entity
Provides callback support through Provides callback support through
lifecycle, interceptor, and validatable Entity Listener and Callback
interfaces methods
Entity Relationships are
unidirectional. Bidirectional Entity Relationships are
relationships are implemented by two bidirectional or unidirectional
unidirectional relationships

73) Difference between list() and iterate() in Hibernate?

Lara Technologies 080-41310124 156


http://javaeasytoall.com

If instances are already be in the session or second-level cache iterate() will


give better performance.
If they are not already cached, iterate() will be slower
than list() and might require many database hits for a simple query

74) Deleting persistent objects

Session.delete() will remove an object's state from the database. Of course,


your application might still hold
a reference to a deleted object. It's best to think of delete() as making a
persistent instance transient.
sess.delete(cat);

75) SQL statements execution order.

1. all entity insertions, in the same order the corresponding objects


were saved using Session.save()
2. all entity updates
3. all collection deletions
4. all collection element deletions, updates and insertions
5. all collection insertions
6. all entity deletions, in the same order the corresponding objects
were deleted using Session.delete()

76) Criteria Query Two Condition

Criteria Query Two Condition- Example


<class name="com.bean.Organization" table="ORGANIZATION">
<id name="orgId" column="ORG_ID" type="long">
<generator class="native"/>
</id>
<property name="organizationName"
column="ORGANISATION_NAME" type="string" length="500"/>
<property name="town" column="TOWN" type="string"
length="200"/>
<property name="statusCode" column="STATUS" type="string"
length="1"/>
</class>
List of organisation where town equals to pune and status = "A".

Lara Technologies 080-41310124 157


http://javaeasytoall.com

List organizationList = session.createCriteria(Organization.class)


.add(Restrictions.eq("town","pune"))
.add(Restrictions.eq("statusCode","A"))
.list();

77) addScalar() method in hibernate...

Double max = (Double) sess.createSQLQuery("select max(cat.weight) as


maxWeight from cats cat")
.addScalar("maxWeight", Hibernate.DOUBLE);
.uniqueResult();

addScalar() method confim that maxWeight is always double type.

This way you don't need to check for it is double or not.

78) Difference between getCurrentSession() and openSession() in


Hibernate ?

getCurrentSession() :
The "current session" refers to a Hibernate Session bound by
Hibernate behind the scenes, to the transaction scope.
A Session is opened when getCurrentSession() is called for the first
time and closed when the transaction ends.
It is also flushed automatically before the transaction commits. You
can call getCurrentSession() as often and anywhere you want as long
as the transaction runs.
To enable this strategy in your Hibernate configuration:

set hibernate.transaction.manager_lookup_class to a lookup strategy


for your JEE container
set hibernate.transaction.factory_class to
org.hibernate.transaction.JTATransactionFactory

Only the Session that you obtained with sf.getCurrentSession() is


flushed and closed automatically.

Lara Technologies 080-41310124 158


http://javaeasytoall.com

Example :
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");

tx.begin();

// Do some work
sf.getCurrentSession().createQuery(...);
sf.getCurrentSession().persist(...);

tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}

openSession() :
If you decide to use manage the Session yourself the go for
sf.openSession() , you have to flush() and close() it.
It does not flush and close() automatically.
Example :
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");

Session session = factory.openSession();

try {
tx.begin();

// Do some work
session.createQuery(...);
session.persist(...);

session.flush(); // Extra work you need to do

tx.commit();
}
catch (RuntimeException e) {

Lara Technologies 080-41310124 159


http://javaeasytoall.com

tx.rollback();
throw e; // or display error message
}
finally {
session.close(); // Extra work you need to do
}

79) Give me simple example of hibernate caching and explain the details
of caching?

caching concept in hibernate is performed internally in


stages...
1)firstlevel(Session) caching
2)Secondlevel(SessionFactory) caching
1)firstlevel(Session) caching:
First-level cache always Associates with the Session
object. Hibernate uses this cache by default. Here, it
processes one transaction after another one, means wont
process one transaction many times. Mainly it reduces the
number of SQL queries it needs to generate within a given
transaction. That is instead of updating after every
modification done in the transaction, it updates the
transaction only at the end of the transaction.

2)Secondlevel(SessionFactory) caching
Second-level cache always associates with the Session
Factory object. While running the transactions, in between
it loads the objects at the Session Factory level, so that
those objects will available to the entire application,
don’t bounds to single user. Since the objects are already
loaded in the cache, whenever an object is returned by the
query, at that time no need to go for a database
transaction. In this way the second level cache works.

80) Difference between session.save() , session.saveOrUpdate() and


session.persist()?

session.save() : Save does an insert and will fail if the primary key is
already persistent.

Lara Technologies 080-41310124 160


http://javaeasytoall.com

session.saveOrUpdate() : saveOrUpdate does a select first to


determine if it needs to do an insert or an update.
Insert data if primary key not exist otherwise update data.

session.persist() : Does the same like session.save().


But session.save() return Serializable object but session.persist()
return void.
session.save() returns the generated identifier (Serializable
object) and session.persist() doesn't.
For Example :
if you do :-
System.out.println(session.save(question));
This will print the generated primary key.
if you do :-
System.out.println(session.persist(question));
Compile time error because session.persist() return void.

Lara Technologies 080-41310124 161


http://javaeasytoall.com

AZAX

Refresh a Page with text field:

From index.html we are getting test.txt by clicking the link and


refreshing the some portion of page by printing the content of the test.txt
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script>
function makeRequest(url)
{
var httpRequest;
if(window.XMLHttpRequest)
{//MOZILA,SAFARI..
httpRequest = new XMLHttpRequest();
if(httpRequest.overrideMimeType)
{
httpRequest.overrideMimeType('text/xml');
}
}
else if(window.ActiveXObject)
{//IE
try
{

Lara Technologies 080-41310124 162


http://javaeasytoall.com

httpRequest = new
ActiveXObject("Msxml12.XMLHTTP");
}
catch(e)
{
try
{
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(!httpRequest)
{
alert("Giving UP:con not create an XMLHTTP instance");
return false;
}
httpRequest.onreadystatechange = function()
{alertContents(httpRequest);};
httpRequest.open('POST',url,true);
httpRequest.setRequestHeader("Content-Type","application/x-
www-form-urlencoded");
httpRequest.send("");
}
function alertContents(httpRequest)
{
if(httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
document.getElementById("lara").innerHTML =
httpRequest.responseText;
}
else
{
alert("There was a problem");
}
}
}

Lara Technologies 080-41310124 163


http://javaeasytoall.com

</script>
<body>
<a href="#" onclick="makeRequest('test.txt')">
Make a request for Text File
</a><br><br>
<div id="lara">LARA TECHNOLOGIES</div>
<br><br><br>
WELCOME TO AZAX
</body>
</html>
test.txt
Hello welcome to lara

Refreshing a page with XML


From index.html we are getting test.xml by clicking the button and
refreshing the some portion of page by printing the content of the
test.xml

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script>
function makeRequest(url)
{
var httpRequest;
if(window.XMLHttpRequest)
{//MOZILA,SAFARI..
httpRequest = new XMLHttpRequest();
if(httpRequest.overrideMimeType)
{
httpRequest.overrideMimeType('text/xml');
}
}

Lara Technologies 080-41310124 164


http://javaeasytoall.com

else if(window.ActiveXObject)
{//IE
try
{
httpRequest = new
ActiveXObject("Msxml12.XMLHTTP");
}
catch(e)
{
try
{
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(!httpRequest)
{
alert("Giving UP:con not create an XMLHTTP instance");
return false;
}
httpRequest.onreadystatechange = function()
{alertContents(httpRequest);};
httpRequest.open('POST',url,true);
httpRequest.setRequestHeader("Content-Type","application/x-
www-form-urlencoded");
httpRequest.send("");
}
function alertContents(httpRequest)
{
if(httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
var xmldoc = httpRequest.responseXML;
var root_node =
xmldoc.getElementsByTagName('root').item(0);
document.getElementById("lara").innerHTML =
root_node.firstChild.data;

Lara Technologies 080-41310124 165


http://javaeasytoall.com

}
else
{
alert("There was a problem");
}
}
}
</script>
<body>
<input type="button" value="CALL XML FILE"
onclick="makeRequest('test.xml')">
<br><br>
<div id="lara">LARA TECHNOLOGIES</div>
<br><br><br>
WELCOME TO AZAX
</body>
</html>
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
hello welcome to lara MANIKANTA
</root>

Refreshing a page with JSP


From index.html we are getting test.jsp by clicking the link and
refreshing the some portion of page by printing the content of the test.jsp

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script>
function makeRequest(url)
{
var httpRequest;

Lara Technologies 080-41310124 166


http://javaeasytoall.com

if(window.XMLHttpRequest)
{//MOZILA,SAFARI..
httpRequest = new XMLHttpRequest();
if(httpRequest.overrideMimeType)
{
httpRequest.overrideMimeType('text/xml');
}
}
else if(window.ActiveXObject)
{//IE
try
{
httpRequest = new
ActiveXObject("Msxml12.XMLHTTP");
}
catch(e)
{
try
{
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(!httpRequest)
{
alert("Giving UP:con not create an XMLHTTP instance");
return false;
}
httpRequest.onreadystatechange = function()
{alertContents(httpRequest);};
httpRequest.open('POST',url,true);
httpRequest.setRequestHeader("Content-Type","application/x-
www-form-urlencoded");
httpRequest.send("");
}
function alertContents(httpRequest)
{
if(httpRequest.readyState == 4)

Lara Technologies 080-41310124 167


http://javaeasytoall.com

{
if(httpRequest.status == 200)
{
document.getElementById("lara").innerHTML =
httpRequest.responseText;
}
else
{
alert("There was a problem");
}
}
}
</script>
<body>
<input type="button" value="CALL JSP FILE"
onclick="makeRequest('test.jsp')">
<br><br>
<div id="lara">LARA TECHNOLOGIES</div>
<br><br><br>
WELCOME TO AZAX
</body>
</html>

test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<body>
<%
out.println("HELLO WELCOME TO LARA");
%>
</body>
</html>

Lara Technologies 080-41310124 168


http://javaeasytoall.com

Refreshing a page with txt,XML,JSP


From index.html we are getting test.txt, test.xml and test.jsp by clicking
the link and refreshing the some portion of page by printing the content of
the test.txt

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script type="text/javascript" language="javascript">
function makeRequest(url) {
var httpRequest;

if (window.XMLHttpRequest) { // Mozilla, Safari, ...


httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}

Lara Technologies 080-41310124 169


http://javaeasytoall.com

if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function()
{ alertContents(httpRequest, url); };
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-
www-form-urlencoded");
httpRequest.send("");

function alertContents(httpRequest, url) {

if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
var str ="";
if(url.substring(url.indexOf('.') + 1) == "xml")
{
var xmldoc = httpRequest.responseXML;
var root_node =
xmldoc.getElementsByTagName('root').item(0);
str = root_node.firstChild.data;
}
else
{
str = httpRequest.responseText;
}
document.getElementById("lara").innerHTML = str;
} else {
alert('There was a problem with the request.');
}
}

}
</script>
<body>

Lara Technologies 080-41310124 170


http://javaeasytoall.com

<input type="button" value="CALL XML FILE"


onclick="makeRequest('test.xml')"><br>
<input type="button" value="CALL JSP FILE"
onclick="makeRequest('test.jsp')"> <br>
<a href="#" onclick="makeRequest('test.txt')">
Make a request for Text File
</a>
<br><br>
<div id="lara">LARA TECHNOLOGIES</div>
<br><br><br>
WELCOME TO AZAX
</body>
</html>
test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<body>
<%
out.println("HELLO WELCOME TO LARA from jsp");
%>

</body>
</html>

Refreshing a page with JSP by passing one parameter

Lara Technologies 080-41310124 171


http://javaeasytoall.com

index.html
<script type="text/javascript" language="javascript">
function makeRequest(url, param) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}

if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function()
{ alertContents(httpRequest); };
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-
www-form-urlencoded");
httpRequest.send("param=" + param);

}
function alertContents(httpRequest) {

if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {

Lara Technologies 080-41310124 172


http://javaeasytoall.com

document.getElementById("lara").innerHTML =
httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
</script>
<a href="#" onclick="makeRequest('test.jsp', 'hello')">Make request to
test.jsp</a>
<br><br><br>

<div id="lara"></div>
test.jsp
<%
out.println(request.getParameter("param" + ",");
out.println("lara");
%>
One Simple Development

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script type="text/javascript" language="javascript">
function makeRequest(url, field) {
var httpRequest;

if (window.XMLHttpRequest) { // Mozilla, Safari, ...


httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}

Lara Technologies 080-41310124 173


http://javaeasytoall.com

else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}

if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}

httpRequest.onreadystatechange = function()
{ populateDistricts(httpRequest); };
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-
www-form-urlencoded");
httpRequest.send("stateId=" + field.value);

function populateDistricts(httpRequest) {

if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {

document.getElementById("districts").innerHTML =
httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}

Lara Technologies 080-41310124 174


http://javaeasytoall.com

</script>

State:<select name="state" onchange="makeRequest('test.jsp', this)">


<option value="0">Pls Select</option>
<option value="1">Karnataka</option>
<option value="2">Andra</option>
</select>
<br><br><br>
<div id="districts"></div>
test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<body>
<%
String id = request.getParameter("stateId");
out.println("<select name='districts'>");
if("1".equals(id))
{
out.println("<option value='blr'>Bangaloore</option>");
out.println("<option value='balr'>BaLary</option>");
}
else if("2".equals(id))
{
out.println("<option value='hyd'>Hyderabad</option>");
out.println("<option value='kdp'>Kadapa</option>");
out.println("<option value='tpt'>Tirupati</option>");
}
out.println("</select>");
%>
</body>
</html>

Lara Technologies 080-41310124 175


http://javaeasytoall.com

test.xml
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<body>
<%
out.println("HELLO WELCOME TO LARA from jsp");
%>

</body>
</html>

test.txt
Hello welcome to lara

Lara Technologies 080-41310124 176

S-ar putea să vă placă și