You are on page 1of 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

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

and may be used in a cluster. ‘Hibernate Criteria Query’. providing an easy to use and powerfull object relational persistence framework for java applications. as well as composite types. it can be expensive to propagate those changes to the rest of the application.  Hibernate is scalable: Hibernate is very performent and due to its dual-layer architecture can be used in the clustered environment.  Support for application transactions: Hibernate supports both long- lived persistance contexts and detach/research and takes care of optimistic locking automatically. It provides three full- featured query facilities those are ‘Hibernate Query Language’.  Support for ultra-fine-grained object models: a rich variety of mappings for collections and dependent objects.  If changes are made to the underlying database schema. but also how to get them out again.  The query language: Hibernate addresses both sides of the problem.0: Hibernate implements the persistance API and quarey language defined by EJB3. not only how to get objects into the database.  Free/openSource: Hibernate is lisensed under the LGPL (Lesser GNU Public Lisesce). inheritance. composition and the java collection framework.  Extra scalability: Hibernate is extremely performant has dual-layer cache architecture. http://javaeasytoall. two members of the Hibernate team are active in the expert group. polymorphism.  No build-time bytecode enhancement: there is no extra code genaration or bytecode processing steps in your build procedure.0 persistence.  Hibernate steps into fill this gap. ‘dialect of the database’.  Ejb3.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. 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.  Hibernate provides support for collections and object relations. Lara Technologies 080-41310124 5 .

which are slightly different to Hibernate’s saveOrUpdate () and saveOrUpdatecopy () operations.  Automatic key generation: Hibernate supports the automatic generation of primary key.  The EJB3 draft specification support for POJO persistance and annotations. composition and the java collection framework.  EJB3-Stylepersistance operation: defines the create () and merge () operations. Hibernate Based Application Architecture: Persistant Objects Sessoion SessionFactory Configuration Query Transaction JDBC Lara Technologies 080-41310124 6 .  Hibernate XML binding enables data to be represented as XML and POJOs interchangeabily.com  Less devolopment time: Hibernate reduces the development timings as it supports inheritance.  Enhanced Criteria query API: with full support for projection/aggregation and subselects. polymorphism. Hibernate3 will support all four operations as methods of the session interface. http://javaeasytoall.

Any one of the database.org’. Then Hibernate can be used to perform operations on the database like select. If you are using web-application then only any one of the webServer. object Relational Management: Hibernate provides a lot of flexibility in use. 4.jar Lara Technologies 080-41310124 7 . Pre requisits to use hibernate: 1. 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. It is called ‘lite’ architecture when we only use the object relational mapping component.com To use Hibernate.jar file 2. 3. transaction Management: 3. For example apache DBCP is used for connection pooling with the Hibernate. Driver JAR file 3. hibernate-3. Updating buildpath: Inorder to use hibernate framework we should update classpath or buildpath with the relavent and dependent JAR files those are: 1. update and delete the records in the table. Hibernate architecture has three main components: 1. Hibernatre is being used with other configuration management and transaction management tools. connection Management: 2. While in ‘full cream’ architecture all the three component Objects Relaational Mappings are used.2. Java Development Kit of J2SE.hibernate. insert. In order to interact with database by using Hibernate need to update classpath or buildpath with relavent jar files. 2. The official website for hibernate is ‘www. http://javaeasytoall. dependent JAR files which are inside lib folder of hibernate-3. For that database 4th type of driver jar file.

Configuration): In order to complete configuration of the of the hibernate we use this class. Configuration (org.hibernate.hibernate. 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.s A single-threaded. short-lived object representing a conversation between the application and the persistent store. used when navigating the object graph or looking up objects by identifier. short-lived object used by the application to specify atomic units of work. JTA or CORBA transaction.Session): Session object is similar to the HttpSession object.com Hibernate API Session (org. used when navigating the object graph or looking up objects by identifier.cfg. A Session might span several Transactions in some cases. Factory for Transaction.cfg. A single-threaded.hibernate. http://javaeasytoall. Transaction (org.Transaction): (Optional) A single-threaded. However. either using the underlying API or Transaction. Holds a mandatory (first-level)cache of persistent objects. transaction demarcation. Lara Technologies 080-41310124 8 . Holds a mandatory (first-level) cache of persistent objects.query): In order to construct HQL queries we use this interface. Factory for Transaction.hibernate.SessionFactory): SessionFactory is a singletone object for entire application there will be one sessinfactory object. Not only this interface we can also use Criteria interface.hibernate. Abstracts application from underlying JDBC. Wraps a JDBC connection. Wraps a JDBC connection. Query(org. short-lived object representing a conversation between the application and the persistent store. SessionFactory (org.

zip. At the time of downloading we will get one zip file i.  Write client program .  Update configuration file with hbm file path.ga.e hibernate. Dialect class. http://javaeasytoall. DriverClassName.xml for your application under classpath. Development steps for Application project: For Every framework there will be one configuration file Eg: for struts struts-config. 6. Use transaction 4. 4.  Take both jar files and update classpath or buildpath (in eclipse) or copy into lib folder of web application. URL.org). 5. Inside this xml file we have to explian about.  There is a website to download (www.com Getting Start with Hibernate:  Hibernate is free to use and it is openSource . Unzip it to the favourable location.xml  First develop one hibernate. Type of 2nd level cache. 3.  Develop “POJO class”(Plain Old Java Object). Username to connect to database. Open hibernate session.config. Start transaction. 2. Inside unzipped folder you can find many folders.2. 3. Commit transaction 5.  For every pojo class develop one hbm (hibernate mapping) file.jar files) are required to develop any hibernate related application.xml. Among them hibernate3. 2. It is similar to usebean or form bean.e core hibernate) and jar files in the lib (hibernate dependence . 1. Password to connect to database.3. Like wise for hibernate also there is one config file i.config. Close the session Lara Technologies 080-41310124 9 .e hibernate-3.jar (i.Inside this. Through this we are updating database type (Dialect means pronouncing same language in different accents).hibernate. 1. we have to follow following steps.

e core hibernate) . http://javaeasytoall. 1.0//EN" "http://hibernate.mysql.pool_size">1</property> <!-. 3. 2.password"></property> <!-.jar (i.0.sourceforge.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.url"> jdbc:mysql://localhost/lara</property> <property name="connection.dialect.cfg.dtd"> <hibernate-configuration> <session-factory> <!-. jar files from lib(hibernate dependence .xml file inside src folder <?xml version='1. Now develop hibernate.jar files) and the Driver jar file.com Developing core java related project: Developing a simple helloworld stand alone application by using mySql database.JDBC connection pool (use the built-in) --> <property name="connection.hibernate.username">root</property> <property name="connection. Go to eclipse and create one core java related project.driver_class"> com.MySQLDialect</property> <!-.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> Lara Technologies 080-41310124 10 .Database connection settings --> <property name="connection.SQL dialect --> <property name="dialect"> org.Driver</property> <property name="connection.net/hibernate-configuration-3.jdbc. Now update the buildpath with hibernate3.

hbm. We want to crate table for Person with column names as (Person_ID.hibernate. Now create a package structure and develop a Pojo object.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-. public class Person { private Integer id.id = id. } public String getPersonName () { return personName. } Lara Technologies 080-41310124 11 . private String personName.com <!-.Drop and re-create the database schema on startup --> <property name="hbm2ddl.cache. PERSON_NAME.xml"/> </session-factory> </hibernate-configuration> 4. public int getId () { return id.auto">create</property> <mapping resource="com/lara/Person.Disable the second-level cache --> <property name="cache.provider_class"> org.lara.NoCacheProvider</property> <!-. http://javaeasytoall.So first develop one Pojo class with all these attributes package com. private Integer personAge. } public void setId (int id) { this. PERSON_AGE).

In hibernate with out primary key we can’t develop any table.com public void setPersonName (String personName) { this. In hbm file we want to take care about all attributes for creating table.net/hibernate-mapping-3.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 .lara. Now develop one hbm file for every Pojo class in one package.personAge = personAge. <?xml version="1.personName = personName.sourceforge. In persons table we want to make PERSON_ID column as autoincrement and primarykey then use id and generator tags.0.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.dtd"> <hibernate-mapping> <class name="com. } public int getPersonAge () { return personAge. } public void setPersonAge (int personAge) { this. } } 5. http://javaeasytoall.0//EN" "http://hibernate.

hibernate. import org. Close the session session. p1. session. Configuration Configuration config = new Configuration ().e MySql4) and run the program.hibernate.com 6. import org.save (p1). //2. // 1. public class Manager { public static void main (String [] args) { Person p1 = new Person ().SessionFactory.configure ().getTransaction ().flush ().commit (). Now start the database (i. Open the session Hibernate SessionFactory sf = config.openSession (). } } 7. config.buildSessionFactory ().setPersonAge (29). Use the Transaction session.hibernate.close (). http://javaeasytoall. import org. p1. Now develop one client programm package com.setPersonName ("RAMESH"). //5.Session.beginTransaction ().cfg.Configuration. Lara Technologies 080-41310124 13 . Commit the transaction session. //4.lara. Start the Transaction session. Session session = sf. //3. //6.

MySQLDialect</property> <!-. 3.Driver</property <property name="connection. Now update the buildpath with hibernate3.password"></property> <!-. jar files from lib(hibernate dependence .driver_class"> com.pool_size">1</property> <!-.sourceforge.net/hibernate-configuration-3. http://javaeasytoall.SQL dialect --> <property name="dialect"> org. 1.url"> jdbc:mysql://localhost/lara</property> <property name="connection.Database connection settings --> <property name="connection.dialect. Now develop hibernate.username">root</property> <property name="connection. Go to eclipse and create one core java related project. 2.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.xml file inside src folder <?xml version='1.com Updating the record in the database tjrough Hibernate: Developing a simple helloworld stand alone application by using MySql database.JDBC connection pool (use the built-in) --> <property name="connection.jar files) and the Driver jar file.e core hibernate) .dtd"> <hibernate-configuration> <session-factory> <!-.jdbc.mysql.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> Lara Technologies 080-41310124 14 .0.0//EN" "http://hibernate.cfg.jar (i.hibernate.

http://javaeasytoall.id = id. PERSON_NAME. PERSON_AGE).hbm.So first develop one Pojo class with all these attributes package com. } public void setId (int id) { this. public class Person { private int id.lara.cache.hibernate. } public void setPersonName (String personName) { Lara Technologies 080-41310124 15 .auto">update</property> <mapping resource="com/lara/Person.xml"/> </session-factory> </hibernate-configuration> 4. private int personAge. We want to crate table for Person with column names as (Person_ID.com <!-.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-. public int getId () { return id.NoCacheProvider</property> <!-.provider_class"> org.Disable the second-level cache --> <property name="cache.Drop and re-create the database schema on startup --> <property name="hbm2ddl. } public String getPersonName () { return personName. private String personName. Now create a package structure and develop a Pojo object.

personAge = personAge.net/hibernate-mapping-3. Now develop one hbm file for every Pojo class in one package. Lara Technologies 080-41310124 16 .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. http://javaeasytoall.dtd"> <hibernate-mapping> <class name="com.sourceforge. <?xml version="1. } } 5. In hbm file we want to take care about all attributes for creating table.0//EN" "http://hibernate.com this. In hibernate with out primary key we can’t develop any table. } public void setPersonAge (int personAge) { this. In persons table we want to make PERSON_ID column as autoincrement and primarykey then use id and generator tags.personName = personName. Now develop one client programm package com.0.lara.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.lara. } public int getPersonAge () { return personAge.

p1.com import org.setPersonName ("RAMESH"). //4.e MySql4) and run the program. import org. Commit the transaction session. p1. Use the Transaction session. //5. config.hibernate. public class Manager { public static void main (String [] args) { Person p1 = new Person (). //3. Close the session session.setPersonAge (29). //6. Lara Technologies 080-41310124 17 .SessionFactory. Open the session Hibernate SessionFactory sf = config.buildSessionFactory ().commit ().hibernate.flush ().openSession (). //2.saveOrUpdate(p1). Now start the database (i.class.cfg.configure ().getTransaction (). Start the Transaction session.load(com.close ().Person. // 1.hibernate. Configuration Configuration config = new Configuration (). Session session = sf.Session.lara. session. http://javaeasytoall. import org. Person p1 = (Person)session. new Integer(id)). } } 7.Configuration.beginTransaction ().

0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.dialect.MySQLDialect</property> <!-. 3. jar files from lib(hibernate dependence .0.jar files) and the Driver jar file. Now update the buildpath with hibernate3.0//EN" "http://hibernate.dtd"> <hibernate-configuration> <session-factory> <!-.cfg.sourceforge.net/hibernate-configuration-3.e core hibernate) .jar (i.url"> jdbc:mysql://localhost/lara</property> <property name="connection.Driver</property <property name="connection. 2.Database connection settings --> <property name="connection. http://javaeasytoall.password"></property> <!-.username">root</property> <property name="connection.xml file inside src folder <?xml version='1.mysql. Now develop hibernate.Enable Hibernate's automatic session context management --> Lara Technologies 080-41310124 18 .pool_size">1</property> <!-. 1.jdbc.JDBC connection pool (use the built-in) --> <property name="connection. Go to eclipse and create one core java related project.SQL dialect --> <property name="dialect"> org.hibernate.com Deleting a recrd through Hibernate program: Developing a simple helloworld stand alone application by using MySql database.driver_class"> com.

NoCacheProvider</property> <!-. PERSON_AGE). private int personAge. public class Person { private int id.auto">create</property> <mapping resource="com/lara/Person. public int getId () { return id.Drop and re-create the database schema on startup --> <property name="hbm2ddl.com <property name="current_session_context_class">thread</property> <!-.lara.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-. PERSON_NAME.provider_class"> org. http://javaeasytoall.Disable the second-level cache --> <property name="cache.cache. We want to crate table for Person with column names as (Person_ID.hibernate. } public void setId (int id) { this. Now create a package structure and develop a Pojo object. Lara Technologies 080-41310124 19 .id = id.xml"/> </session-factory> </hibernate-configuration> 4. private String personName.hbm. } public String getPersonName () { return personName.So first develop one Pojo class with all these attributes package com.

Now develop one hbm file for every Pojo class in one package. In hibernate with out primary key we can’t develop any table.0.personName = personName.com } public void setPersonName (String personName) { this.lara.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.personAge = personAge.dtd"> <hibernate-mapping> <class name="com.sourceforge.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. http://javaeasytoall. } public int getPersonAge () { return personAge. In hbm file we want to take care about all attributes for creating table. } public void setPersonAge (int personAge) { this. <?xml version="1. Now develop one client programm Lara Technologies 080-41310124 20 .0//EN" "http://hibernate.net/hibernate-mapping-3. } } 5. In persons table we want to make PERSON_ID column as autoincrement and primarykey then use id and generator tags.

p1. import org.buildSessionFactory ().println(“ Deleted a record from table. //6.configure (). Commit the transaction session. import org. config. new Integer(id)).openSession ().close ().”).setPersonAge (29). //5. Open the session Hibernate SessionFactory sf = config.class. //3. Start the Transaction session.cfg. Configuration Configuration config = new Configuration (). // 1. //4. System.hibernate.commit (). session.Configuration.setPersonName ("RAMESH").delete(p1). //2. Close the session session.hibernate.load(Person. p1.hibernate. Person p1 = (Person)session. Session session = sf.flush ().beginTransaction ().lara.Session. import org. public class Manager { public static void main (String [] args) { Person p1 = new Person (). Use the Transaction session.out.SessionFactory.getTransaction (). } } Lara Technologies 080-41310124 21 .com package com. http://javaeasytoall.

username">root</property> <property name="connection.jar file) in to the “lib” folder of our web application.0//EN" "http://hibernate.cfg. driver.e MySql4) and run the program. hibernatedependence.JDBC connection pool (use the built-in) --> Lara Technologies 080-41310124 22 . and we want to insert.net/hibernate-configuration-3.url"> dbc:mysql://localhost/lara</property> <property name="connection.mysql. Now start the database (i.delete and edit the already stored record.Driver</property> <property name="connection.0.PRODUCT_QUANTITY and PRODUCT_ID. 1.dtd"> <hibernate-configuration> <session-factory> <!-. 2.PRODUCT_PRICE. 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.driver_class"> com. Copy all relavent jar files(i.jar.jdbc.password"></property> <!-.com 7.e corehibernate.sourceforge.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3. http://javaeasytoall.jar files.Database connection settings --> <property name="connection. Now develop hibernate.xml in “src” folder <?xml version='1.

private int productQuantity.cache.hbm.hibernate.auto">update</property> <mapping resource="com/lara/Product.MySQLDialect</property> <!-.hibernate. } public void setId(int id) { Lara Technologies 080-41310124 23 .SQL dialect --> <property name="dialect"> org.lara. Now create one package structure in “src” folder and develop one Pojo class.com <property name="connection. private double productPrice.provider_class"> org.Disable the second-level cache --> <property name="cache. public class Product { private int id.NoCacheProvider</property> <!-.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.dialect. http://javaeasytoall.Drop and re-create the database schema on startup --> <property name="hbm2ddl. package com.xml"/> </session-factory> </hibernate-configuration> 3.pool_size">1</property> <!-. public int getId() { return id. private String productName.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.

} public String getProductName() { return productName. } public void setProductName(String productName) { this.hbm. } public void setProductPrice(double productPrice) { this. http://javaeasytoall.id = id.0//EN" "http://hibernate.com this.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 .xml) file for every Pojo class.sourceforge. Now develop hbm(Product.productPrice = productPrice.dtd"> <hibernate-mapping> <class name="com. } } 4.0. } public void setProductQuantity(int productQuantity) { this. <?xml version="1.net/hibernate-mapping-3. } public int getProductQuantity() { return productQuantity. } public double getProductPrice() { return productPrice.productName = productName.productQuantity = productQuantity.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.lara.

jsp">EDIT</a><br> <a href="delete.jsp page is for updating the already existing record.jsp">DELETE</a><br> </body> add.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 . index. Now develop one Jsp file and use it.jsp page is for inserting the values into the table. edit.com </class> </hibernate-mapping> 5. http://javaeasytoall.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. add.jsp">INSERT</a><br> <a href="edit.jsp <body> <a href="add.

com delete.getParameter("productName").servlet.servlet. import org. Product pdr = new Product().Servlet { static final long serialVersionUID = 1L.HttpServletRequest. public InsertServlet() { super().Configuration.getParameter("productQuantity").http.HttpServletResponse. import javax.cfg.lara.http.servlet. HttpServletResponse response)throws ServletException. import org. } protected void doPost(HttpServletRequest request. import java.IOException.getParameter("productPrice"). public class InsertServlet extends javax.servlet.hibernate. String pQty= request. delete.java package com.io. Develop servlets for every jsp pages.Session.servlet. import org.jsp <body> <form action="DeleteServlet" method="post"> Id:<input type="text" name="id"><br> <input type="submit" value="DELETE"> </form> </body> 3. Lara Technologies 080-41310124 26 . http://javaeasytoall. import javax. import javax. String pPrice = request.hibernate.http.PrintWriter. InsertServlet.io. import java.ServletException.hibernate.SessionFactory.jsp is for deleting the record from table. IOException { String pName = request.HttpServlet implements javax.

config.close().http.lara.PrintWriter. session.SessionFactory.Servlet Lara Technologies 080-41310124 27 .HttpServlet implements javax.servlet. } } UpdateServlet.buildSessionFactory().save(pdr).com pdr. import org.java package com.setProductName(pName).IOException. http://javaeasytoall.servlet.io.setProductPrice(Double. import javax.cfg. import javax. Configuration config = new Configuration(). pdr.HttpServletRequest.beginTransaction().http.http. import java. import org.getWriter().close(). out.println("PRODUCT SAVED").parseInt(pQty)).openSession(). session. session.getTransaction(). pdr.servlet.ServletException.commit().flush().HttpServletResponse. public class UpdateServlet extends javax.io.Session. PrintWriter out = response. out.parseDouble(pPrice)). session.configure().Configuration. Session session = sf.servlet. import org.setProductQuantity(Integer.hibernate. SessionFactory sf = config.servlet.hibernate. import java.hibernate. session. import javax.

p1.load(Product.println("<br><a href=index. HttpServletResponse response) throws ServletException. out.getParameter("productPrice"). PrintWriter out = response. Integer. http://javaeasytoall. config.beginTransaction().getParameter("productQuantity").getParameter("id").getParameter("productName"). p1.parseDouble(pPrice)). out. public UpdateServlet() { super(). session.setProductName(pName).configure(). String pName = request. Session session = sf. } protected void doPost(HttpServletRequest request.setProductQuantity(Integer. Product p1 = (Product)session.commit().openSession(). } Lara Technologies 080-41310124 28 .getWriter().parseInt(id)). String pQty = request.saveOrUpdate(p1). SessionFactory sf = config.buildSessionFactory(). Configuration config = new Configuration().setProductPrice(Double.getTransaction().close().class.parseInt(pQty)).close().jsp>HOME</a>").println("PRODUCT UPDATED"). String pPrice = request. session. session. out. session.flush(). session. IOException { String id = request. p1.com { static final long serialVersionUID = 1L.

servlet.configure(). Configuration config = new Configuration(). config.buildSessionFactory().ServletException.Session.hibernate.parseInt(id)). IOException { String id = request.com } DeleteServlet.lara. import java.servlet.HttpServlet implements javax. import javax.HttpServletResponse.servlet.SessionFactory.java package com.delete(p1).io.Servlet { static final long serialVersionUID = 1L. HttpServletResponse response) throws ServletException.getParameter("id"). SessionFactory sf = config. import javax. Lara Technologies 080-41310124 29 .servlet.IOException. Integer. public DeleteServlet() { super().HttpServletRequest. session. import javax. session.class.http.hibernate. http://javaeasytoall.io. Product p1 = (Product)session.servlet. import org. } protected void doPost(HttpServletRequest request.PrintWriter.hibernate.openSession(). import org.load(Product.cfg.http. public class DeleteServlet extends javax.beginTransaction(). import org.http.Configuration. Session session = sf. import java.

e MySql4) and run the “index.url"> jdbc:oracle:thin:@localhost:1521:XE</property> Lara Technologies 080-41310124 30 . ADDRESS_STATE. hibernate.cfg.dtd"> <hibernate-configuration> <session-factory> <!-.jsp”. ADDRESS_STREETNO. Now start the database(i.jsp>HOME</a>").jdbc. PrintWriter out = response.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.println("<br><a href=index. out.update. ADDRESS_HOUSENO.driver_class"> oracle.e insert.commit().net/hibernate-configuration-3.delete. ADDRESS_CITY.getWriter().search: In this application we are using Oracle10g database and we want to create table for ADDRESSES with column names as ADDRESS_ID. and ADDRESS_PINCODENO. One more Example for how to devlop hibernate app in web-app by doing all the operations i. session.0.OracleDriver</property> <property name="connection. session.driver.println("PRODUCT DELETED").sourceforge.flush().close(). http://javaeasytoall. ADDRESS_COUNTRY.close(). out.0//EN" "http://hibernate.xml <?xml version='1. } } 4.list.Database connection settings --> <property name="connection.com session. out.getTransaction().

xml"/> </session-factory> </hibernate-configuration> Address.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.pool_size">1</property> <!-.NoCacheProvider</property> <!-. public class Address { private Integer Id. private String streetNo.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.auto">update</property> <mapping resource="com/lara/Address.Disable the second-level cache --> <property name="cache.cache.Drop and re-create the database schema on startup --> <property name="hbm2ddl.hbm.JDBC connection pool (use the built-in) --> <property name="connection.SQL dialect --> <property name="dialect"> org.java package com.password">great123</property> <!-.OracleDialect</property> <!-.username">system</property> <property name="connection.dialect.hibernate.lara. http://javaeasytoall.provider_class"> org. Lara Technologies 080-41310124 31 .com <property name="connection. private String houseNo.hibernate.

private String state.streetNo = streetNo.houseNo = houseNo.com private String city. http://javaeasytoall.city = city. } public void setCountry(String country) { this. } public void setId(Integer id) { Id = id. public Integer getId() { return Id. Lara Technologies 080-41310124 32 . } public String getState() { return state. } public void setStreetNo(String streetNo) { this. private String country. } public String getCity() { return city. } public void setState(String state) { this. } public String getHouseNo() { return houseNo. } public String getStreetNo() { return streetNo. } public void setCity(String city) { this.state = state. private long pinCodeNo. } public void setHouseNo(String houseNo) { this. } public String getCountry() { return country.country = country.

lara.com } public long getPinCodeNo() { return pinCodeNo. index.net/hibernate-mapping-3.hbm.xml <?xml version="1.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. } public void setPinCodeNo(long pinCodeNo) { this.sourceforge.0.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.dtd"> <hibernate-mapping> <class name="com.pinCodeNo = pinCodeNo. } } Address.jsp Lara Technologies 080-41310124 33 . http://javaeasytoall.0//EN" "http://hibernate.

add. search.jsp">SEARCH</a> </body> add.jsp">Insert</a><br> <a href="ListServlet">LIST</a><br> <a href="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 .jsp is for searching the particular record in the table by selsecting the column names and giving the text to search. http://javaeasytoall.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.com <body> <a href="add.jsp is for inserting the values into the ADDRESSES table.

http.getParameter("city"). import javax.hibernate. Lara Technologies 080-41310124 35 . public class InsertServlet extends javax. import java. import org. http://javaeasytoall. If we want to insert the servlet then we to call save() by passing the object.io.hibernate.servlet.lara.servlet.SessionFactory.HttpServletResponse.Servlet { static final long serialVersionUID = 1L.getParameter("country").getParameter("pinCodeNo").getParameter("state").HttpServletRequest. import javax.http.hibernate.io. String country=request.http. import org. } protected void doPost(HttpServletRequest request.getParameter("streetNo").ServletException. String pinCodeNo=request. String streetNo=request. String city=request.com PinCodeNo</option> </select><br> SearchText: <input type="text" name="searchText"> <input type="submit" value="Search"> </form> </body> InsertServlet.cfg.servlet.Configuration.servlet. import java.IOException. public InsertServlet() { super().HttpServlet implements javax. import org. String state=request.java is for inserting the values into the table.PrintWriter.Session.getParameter("houseNo"). IOException { String houseNo=request. InsertServlet.java package com. Address adr=new Address().classic. HttpServletResponse response) throws ServletException.servlet. import javax.

import java.com adr. SessionFactory sf = config. adr. Session session = sf.classic.close(). session.hibernate.openSession().setHouseNo(houseNo). If we want to update the record then we want to call saveOrUpdate() by passing the object.io. adr. import org.io.IOException.servlet.beginTransaction().close().setPinCodeNo(Long.ServletException.HttpServletRequest. session.println("ADDRESS SAVED").hibernate. config.Configuration.servlet.servlet.java is for editing the particular record in the table. adr. UpdateServlet. out.servlet. http://javaeasytoall. public class UpdateServlet extends javax. import javax.PrintWriter.java package com. session.getWriter().save(adr). adr.lara. adr.SessionFactory. session.servlet. session.setState(state).Session.http. import org. PrintWriter out = response.getTransaction(). out.configure(). Configuration config = new Configuration().flush().hibernate.http.HttpServletResponse.parseLong(pinCodeNo)).setStreetNo(streetNo). import java.HttpServlet implements javax.cfg. import javax. } } UpdateServlet.Servlet Lara Technologies 080-41310124 36 .buildSessionFactory(). import org.setCity(city).setCountry(country).http. import javax.commit().

configure().getParameter("country").commit(). String pinCodeNo=request.setCity(city).getParameter("streetNo").setPinCodeNo(Long.com { static final long serialVersionUID = 1L. adr. HttpServletResponse response) throws ServletException. } protected void doPost(HttpServletRequest request. adr.getParameter("pinCodeNo"). adr. String streetNo=request.setStreetNo(streetNo). session. adr.getParameter("recordId").setId(new Integer(id)). Address adr=new Address(). adr.flush().saveOrUpdate(adr). session. Lara Technologies 080-41310124 37 .getParameter("houseNo"). http://javaeasytoall.setState(state). Configuration config = new Configuration(). SessionFactory sf = config. adr.setHouseNo(houseNo). String state=request.getParameter("city"). String city=request. String houseNo=request. IOException { String id = request.setCountry(country).getParameter("state").getTransaction(). session. Session session = sf.buildSessionFactory(). config. session. session. String country=request. public UpdateServlet() { super(). adr.close().openSession().parseLong(pinCodeNo)).beginTransaction().

import org. public class ListServlet extends javax. import org.http.IOException. out.java is for listing all the records from table.http.servlet.cfg.io.class).com PrintWriter out = response.Expression.hibernate. } Lara Technologies 080-41310124 38 .hibernate. ListServlet. out.PrintWriter.io.hibernate.Session.http. out.Criteria.servlet.util.criterion.HttpServletResponse. } } ListServlet.ServletException.Configuration.println("<a href='index. import java. import javax.servlet. Eg: session.HttpServlet implements javax. import org.servlet.lara.println("ADDRESS SAVED<br>"). import org.hibernate. In this application we are using Criteria.Servlet { static final long serialVersionUID = 1L. out. import java.hibernate. http://javaeasytoall. import org.close(). public ListServlet() { super().If we want to create object for Criteria interface then there is a method createCriteria () which there inside the session class.println("<a href='ListServlet'>ListRecordHome</a>").List.HttpServletRequest.java package com.createCriteria(Address. If we want to list all the records then we want to use Criteria interface or Query interface. import javax.getWriter().SessionFactory. import javax. import java.classic.jsp'>Home</a>").servlet.

println("<b>STATE</b>").println("</td>"). out. out.println("<td>"). out. session.println("</td>"). out.println("<td>").println("<td>").println("<tr>"). config. out. Session session = sf.println("</td>").getWriter(). SessionFactory sf = config. out.println("<b>HOUSENO</b>").getParameter("searchCriteria").println("</td>"). out.getParameter("searchText").println("<b>CITY</b>"). out.configure(). out. out.println("<td>"). http://javaeasytoall. out.println("</tr>"). Configuration config = new Configuration().println("<b>COUNTRY</b>").println("<b>STREETNO</b>").println("<td>").println("</td>").println("<table border='1'>"). out. out. out. String st = request. out. out.buildSessionFactory().println("<td>"). out. out. IOException { Address add= new Address().println("</td>").println("</td>").openSession().println("<b>PINCODENO</b>"). out. out. out. out.beginTransaction(). out. PrintWriter out = response. out. Lara Technologies 080-41310124 39 .println("<b>ID</b>").println("<td>"). String sc = request.com protected void doGet(HttpServletRequest request. HttpServletResponse response) throws ServletException.

st)).println("<td>").println("</td>"). out. out.println(add.createCriteria(Address. out.println("<td>"). } out.println("</td>"). out. out.println(add. out. out. out.println("<td>").list().println("</td>"). out.getId()).getCity()).println("</table>").getId()+"'>").println(add.getCountry()). out.sql(sc+"='"+st+"'"). out.println("<td>"). out.getStreetNo()). out. for(int i=0.println(add.println("</td>").get(i).add(Expression.i++) { add = (Address)list.println("<td>").com Criteria ctr = session.println("</tr>").println("<a href='index.i<list.println(add.jsp'>Home</a>").println("<tr>"). out. out.getHouseNo()). List list = ctr.println("</a>"). Expression.println("<td>"). out. out. out. out. out.println(add. http://javaeasytoall. ctr.eq(sc.println("</td>").println("<a href='DetailedServlet?recordId=" +add. out.getState()). out.getPinCodeNo()).class).size().println("</td>"). out.println(add.println("</td>").println("<td>"). out. Lara Technologies 080-41310124 40 . out. out.

HttpServletResponse.HttpServlet implements javax.HttpServletRequest.SessionFactory. DetailedServlet. import org. } protected void doGet(HttpServletRequest request.configure(). http://javaeasytoall.getParameter("recordId"). import javax. import org. import javax.java package com. config.servlet. SessionFactory sf = config.cfg. Lara Technologies 080-41310124 41 .hibernate.com session. import javax. Configuration config = new Configuration(). } } DetailedServlet. IOException { String recordId = request.io.Configuration. import org.servlet. session. public class DetailedServlet extends javax.getTransaction().for this we want to use load () method which there inside the session class.http. import java.java is for if we select one record then it want to display all the columns from the table. public DetailedServlet() { super().hibernate.PrintWriter.flush().http. HttpServletResponse response) throws ServletException.close().Session.classic.commit().ServletException.io.hibernate.Servlet { static final long serialVersionUID = 1L.servlet.buildSessionFactory().lara.servlet.servlet. session.IOException. import java.http.

http.println("State:"+add.HttpServletResponse.getStreetNo()+"<br>").println("<a href='DisplayForEdit?recordId=" +add. import java.PrintWriter. out. session.commit().servlet.http.println("<a href='index.servlet. out.getId()+"'>Delete</a>").getCountry()+"<br>"). out. out.getHouseNo()+"<br>"). } } DeleteServlet.io.java is for deleting the particular record.println("StreetNo:"+add. Lara Technologies 080-41310124 42 . out. out. import java.flush().getPinCodeNo()+"<br>").openSession(). import javax. import javax.println("City:"+add.println("<a href='DeleteServlet?recordId=" +add. out.getWriter().servlet.getTransaction().lara.beginTransaction().If we want to delete one record then we want to call the delete() by passing the object .java package com. out.load(Address.io.println("Country:"+add.ServletException. new Integer(recordId)).HttpServletRequest. session. session. import javax.getState()+"<br>").jsp'>Home</a>").com Session session = sf.class. PrintWriter out = response.close().getId()+"'>Edit</a>").IOException. DeleteServlet.println("HouseNo:"+add. out. out. session.println("PINCODENO:"+add. http://javaeasytoall.println("<a href='ListServlet'>ListRecordHome</a>"). Address add = (Address)session.getCity()+"<br>").

hibernate.configure().getParameter("recordId").hibernate. out. session. add.hibernate. out.getTransaction().classic.SessionFactory.close().flush(). public DeleteServlet() { super(). session. HttpServletResponse response) throws ServletException.delete(add).cfg.buildSessionFactory().beginTransaction(). import org.servlet. SessionFactory sf = config.Servlet { static final long serialVersionUID = 1L.commit().println("ADDRESS DELETED").http. import org. PrintWriter out = response. Address add = new Address().println("<a href='index. http://javaeasytoall. out. config. } Lara Technologies 080-41310124 43 . session. session.Session. public class DeleteServlet extends javax.openSession(). Configuration config = new Configuration().Configuration.servlet.com import org.close().println("<a href='ListServlet'>ListRecordHome</a>"). IOException { String id = request.setId(new Integer(id)).HttpServlet implements javax.getWriter(). session. } protected void doGet(HttpServletRequest request.jsp'>Home</a>"). Session session = sf. out.

Configuration config = new Configuration(). import org.hibernate.PrintWriter.classic. config. DisplayForEdit.hibernate.HttpServletRequest.Servlet { static final long serialVersionUID = 1L.lara.cfg.http. session.hibernate. public class DisplayForEdit extends javax.servlet. import org. IOException { String recordId = request.servlet.io.openSession().SessionFactory.IOException.servlet. import org.beginTransaction(). Lara Technologies 080-41310124 44 . import java. import javax. import java.configure().HttpServletResponse.getWriter().Session.ServletException. Session session = sf. PrintWriter out = response. public DisplayForEdit() { super(). import javax. http://javaeasytoall.java is for modifying the particular record in the table.HttpServlet implements javax.java package com. HttpServletResponse response) throws ServletException.getParameter("recordId").servlet.http.http.Configuration.com } DisplayForEdit. } protected void doGet(HttpServletRequest request. SessionFactory sf = config.servlet.io. import javax.buildSessionFactory().

seqhilo Lara Technologies 080-41310124 45 .println("<input type='text' name='houseNo' value='" +add.getStreetNo()+"'><br>").class. out. session.println("<input type='hidden' name='recordId' value='" +add. hilo 2. out. out. out.getCountry()+"'><br>"). session.println("PinCodeNo:").println("</form>"). out. new Integer(recordId)). out.println("State").println("City").println("<input type='text' name='state' value='" +add. out.commit().com Address add = (Address)session.getHouseNo()+"'><br>").getState()+"'><br>").getTransaction(). out.println("<input type='text' name='streetNo' value='" +add.load(Address. out. http://javaeasytoall. out.println("StreetNo:").getCity()+"'><br>"). session.flush().println("HouseNo:").getPinCodeNo()+"'><br>"). out. out.println("<input type='text' name='country' value='" +add.println("<form action='UpdateServlet' method='post'>").println("<input type='text' name='pinCodeNo' value='" +add.println("<input type='submit' value='UPDATE'>"). } } What are all the algorithms for attribute “class” of “generator ” tag of “id” tag ?  The types of algorithms are: 1.getId()+"'><br>").println("Country"). out. out. out.println("<input type='text' name='city' value='" +add.close(). out.

com 3.dtd"> <hibernate-configuration> <session-factory> <!-.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.provider_class"> Lara Technologies 080-41310124 46 .xml <?xml version='1.jdbc.0.Disable the second-level cache --> <property name="cache.username">system</property> <property name="connection. select Eg: For testing the algorithms using Oracle10g database hibernate.password">great123</property> <!-. sequence 6.pool_size">1</property> <!-.net/hibernate-configuration-3.JDBC connection pool (use the built-in) --> <property name="connection.SQL dialect --> <property name="dialect"> org.driver.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3. guid 5.cg.sourceforge.hibernate.dialect.Database connection settings --> <property name="connection.0//EN" "http://hibernate. http://javaeasytoall. identity 7.OracleDialect</property> <!-.driver_class"> oracle.OracleDriver</property> <property name="connection.url"> jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection. uuid 4.

private Double bookPrice. } public void setId(Integer id) { this.cache.bookName = bookName.auto">create</property> <mapping resource="com/lara/Book.Drop and re-create the database schema on startup --> <property name="hbm2ddl.NoCacheProvider </property> <!-.hibernate. } public void setBookName(String bookName) { this.hbm.id = id.com org. public class Book { private Integer id.xml"/> </session-factory> </hibernate-configuration> Book. public Integer getId() { return id.java package com.lara. } public String getBookAuther() { return bookAuther. private String bookName. } public String getBookName() { return bookName. Lara Technologies 080-41310124 47 . http://javaeasytoall. private String bookAuther.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.

hbm.net/hibernate-mapping-3.dtd"> <hibernate-mapping> <class name="com.lara.xml <?xml version="1.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.0//EN" "http://hibernate.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0.jsp <body> <form action=” AddBookServlet” method=”post”> Lara Technologies 080-41310124 48 .bookPrice = bookPrice.com } public void setBookAuther(String bookAuther) { this.sourceforge. } } Book.bookAuther = bookAuther. http://javaeasytoall. } public Double getBookPrice() { return bookPrice. } public void setBookPrice(Double bookPrice) { this.

} protected void doPost(HttpServletRequest request. IOException { String id=request. Lara Technologies 080-41310124 49 .hibernate.java package com. Book book = new Book(). import org.classic. import org. import java. http://javaeasytoall. import org. public class AddBookServlet { public void AddBookServlet() { super().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. import java. book. HttpServletResponse response) throws ServletException.Configuration.cfg.getParameter(“name”).Session.io.servlet.IOException. import javax. String name=request.lara.hibernate. import javax.ServletException.setId(100).http.servlet.SessionFactory.getParameter(“auther”).getParameter(“id”).hibernate.io.http.PrintWriter.getParameter(“price”).HttpServletResponse. import javax. String price=request.servlet.HttpServletRequest. String auther=request.

getTransaction(). session. session.setBookName("JAVA"). session.increment these algorithms will support all the databases.commit().xml"). PrintWriter out=response. session.println(“check in the database.50). SessionFactory sf = config.assigned.cfg.setBookPrice(450. Session session = sf.close().flush().setBookAuther("MAHESH").beginTransaction(). session. config.com book. 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.”).buildSessionFactory(). book.openSession(). book.configure("config/hibernate. Lara Technologies 080-41310124 50 .save(book). http://javaeasytoall. Out. } } All algorithms will not support all the databases only few algorithms only support particular databases. Configuration config = new Configuration().getWriter().

configure("config/hibernate.save-update. config.e foreignkey but we will get data The generated query is create table USER_DETAILS ( “USER_ID” VARCHAR2(255).refresh. 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. Cascade types: all. PRIMARYKEY(“USER_ID”)ENABLE ) If we give constrained=”true” then we will get refrencekey i.xml from src folder to separate folder.cfg.merge.replicate.com How to separate cfg.delete. EG: Src| |----cfg| |----hibernate. This option affects the order in which save() and delete() are cascaded.xml").create. If we give constrained=”false” then in USER_DETAILS table we will not get refrencekey i. “USER_ADDRESS” VARCHAR2(255). http://javaeasytoall. “USER_EDUCATION” VARCHAR2(255).evict.e foreignkey and data Lara Technologies 080-41310124 51 .cfg. constrained (optional) specifies that a foreign key constraint on the primary key of the mapped table references the table of the associated class.xml Now come to the program Configuration config = new Configuration(). and determines whether the association may be proxied (it is also used by the schema export tool). “USER_DESIGNATION” VARCHAR2(255).lock.

1.sourceforge. (a) One table per Class hierarchy (b) One table per Sub-Class (c) One table per Concreate-Class 3. PRIMARYKEY(“USER_ID”)ENABLE CONSTRAINT “FK24CC75E74607B17” FOREIGNKEY(“USER_ID”) REFERENCES “USERS”(“USER_ID”) ENABLE ) Mappings are mainly threee types they are: 1.0//EN" "http://hibernate. “USER_DESIGNATION” VARCHAR2(255).0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.dtd"> <hibernate-configuration> Lara Technologies 080-41310124 52 .0.net/hibernate-configuration-3. “USER_ADDRESS” VARCHAR2(255).com create table USER_DETAILS ( “USER_ID” VARCHAR2(255)NOT NULL ENABLE.cfg.xml <?xml version='1. http://javaeasytoall. “USER_EDUCATION” VARCHAR2(255). Relational Mapping (a) One-to-One Mapping (b) One-to-Many and Many-to-one Mapping (c) Many-to-many Mapping 2.(a) One-to-One Mapping: hibernate. Polymorphic Mapping. Component Mapping.

OracleDriver</property> <property name="connection.java Lara Technologies 080-41310124 53 .pool_size">1</property> <!-.auto">create</property> <mapping resource="com/lara/Person.NoCacheProvider</property> <!-.password">great123</property> <!-.hbm.driver_class"> oracle. http://javaeasytoall.com <session-factory> <!-.dialect.SQL dialect --> <property name="dialect"> org.Database connection settings --> <property name="connection.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.OracleDialect</property> <!-.hibernate.username">system</property> <property name="connection.Drop and re-create the database schema on startup --> <property name="hbm2ddl.cache.driver.JDBC connection pool (use the built-in) --> <property name="connection.hbm.hibernate.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.xml"/> </session-factory> </hibernate-configuration> Person.xml"/> <mapping resource="com/lara/ Mail.provider_class"> org.Disable the second-level cache --> <property name="cache.url"> jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.jdbc.

} public void setPersonFirstName(String personFirstName) { this. } public String getPersonLastName() { return personLastName. public class Person { private String personId.personId = personId.personLastName = personLastName. } public Integer getPersonAge() { return personAge. } public void setPersonId(String userId) { this. private String personLastName. } public void setMailId(Mail mailId) { Lara Technologies 080-41310124 54 .com package com. public String getPersonId () { return personId.personFirstName = personFirstName.personAge = personAge. } public void setPersonLastName(String personLastName) { this. private Mail mailId.lara. http://javaeasytoall. } public Mail getMailId() { return mailId. } public String getPersonFirstName() { return personFirstName. private Integer personAge. } public void setPersonAge(Integer personAge) { this. private String personFirstName.

private Date createdTime. } public void setPassword(String password) { this. mailId = mailId. private String personId. public class Mail { private String mailId.createdTime = createdTime. } Lara Technologies 080-41310124 55 .lara.com this. } public void setCreatedTime(String createdTime) { this.java package com. } public void setMailId(String userId) { this. private Person person.mailId = mailId. http://javaeasytoall. } public void setPerson(Person person) { this. } public String getPassword() { return password. public String getMailId() { return mailId. } public Person getPerson() { return person. person = person. } } Mail.password = password. private String password. } public Date getCreatedTime() { return createdTime.

lara.xml <?xml version="1.hbm. } } User.Mail" cascade="all"/> </class> </hibernate-mapping> Mail.lara.xml <?xml version="1. http://javaeasytoall.0.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.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.0//EN" "http://hibernate.personId = personId.hbm. } public void setPersonId(String personId) { this.0//EN" Lara Technologies 080-41310124 56 .net/hibernate-mapping-3.dtd"> <hibernate-mapping> <class name="com.com public String getPersonId() { return personId.sourceforge.

lara.Configuration.Session. import org.lara.setPassword("abcxyz").lara.hibernate. Lara Technologies 080-41310124 57 .com "http://hibernate. mail.SessionFactory.sourceforge.net/hibernate-mapping-3.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. import org. mail. import org.setPerson (p1).java package com. mail.com").hibernate. mail.cfg. public class Manager { public static void main(String[] args) { Mail mail = new Mail().dtd"> <hibernate-mapping> <class name="com.hibernate.setCreatedTime("22-jan-2009").Person" constrained="true"/> </class> </hibernate-mapping> Manager.setMailId ("abc@abc.0. http://javaeasytoall.

0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3. p1.save(p1). Person p1= new Person(). SessionFactory sf = config.setPersonLastName("def").net/hibernate-configuration-3.xml <?xml version='1. http://javaeasytoall.dtd"> <hibernate-configuration> <session-factory> Lara Technologies 080-41310124 58 .getTransaction().beginTransaction().sourceforge.cfg.openSession(). p1. session. p1. session.flush().com mail.setPersonFirstName("abc").setMailId(("abc@abc. session. p1.com").setPersonId("p101"). Configuration config = new Configuration().0//EN" "http://hibernate.setPersonId("p101"). Session session = sf.commit(). p1.close().0. config. session. } } Example2: hibernate.buildSessionFactory(). session.configure().setPersonAge (28).

driver_class"> oracle.java package com.JDBC connection pool (use the built-in) --> <property name="connection.cache.pool_size">1</property> <!-.hibernate.provider_class"> org.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.Disable the second-level cache --> <property name="cache.Database connection settings --> <property name="connection.com <!-.xml"/> <mapping resource="com/lara/ UserDetails.username">system</property> <property name="connection.dialect.SQL dialect --> <property name="dialect"> org.OracleDialect</property> <!-.NoCacheProvider</property> <!-. http://javaeasytoall.hbm.jdbc.OracleDriver</property> <property name="connection. Lara Technologies 080-41310124 59 .driver.xml"/> </session-factory> </hibernate-configuration> User.hibernate.Drop and re-create the database schema on startup --> <property name="hbm2ddl.hbm.auto">create</property> <mapping resource="com/lara/User.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.lara.url"> jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.password">great123</property> <!-.

public String getUserId() { return userId. private Integer userAge. } public void setUserId(String userId) { this. private String userLastName. private String userMobileNo. } public Integer getUserAge() { return userAge. private UserDetails userDetails.userAge = userAge. } public void setUserEmail(String userEmail) { this.userId = userId. } Lara Technologies 080-41310124 60 . } public void setUserLastName(String userLastName) { this. } public String getUserEmail() { return userEmail. private String userEmail. private String userFirstName. } public String getUserLastName() { return userLastName. } public String getUserFirstName() { return userFirstName.userFirstName = userFirstName. } public void setUserAge(Integer userAge) { this. http://javaeasytoall.userEmail = userEmail.userLastName = userLastName. } public void setUserFirstName(String userFirstName) { this.com public class User { private String userId.

userMobileNo = userMobileNo. } public void setUserDetails(UserDetails userDetails) { this. } public String getEduc() { return educ. private User user. private String address.userDetails = userDetails. public class UserDetails { private String userId. } public User getUser() { return user.lara.com public String getUserMobileNo() { return userMobileNo. } public UserDetails getUserDetails() { return userDetails. http://javaeasytoall. } public void setUser(User user) { this. private String educ.user = user. } public void setUserMobileNo(String userMobileNo) { this. } } UserDetails.userId = userId. private String designation. Lara Technologies 080-41310124 61 .java package com. public String getUserId() { return userId. } public void setUserId(String userId) { this.

sourceforge.dtd"> <hibernate-mapping> <class name="com.net/hibernate-mapping-3. } } User. http://javaeasytoall.lara.0//EN" "http://hibernate. } public String getAddress() { return address.lara.0.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.hbm.UserDetails" cascade="all"/> Lara Technologies 080-41310124 62 .designation = designation. } public void setAddress(String address) { this. } public void setDesignation(String designation) { this.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.address = address. } public String getDesignation() { return designation.xml <?xml version="1.com } public void setEduc(String educ) { this.educ = educ.

SessionFactory.0//EN" "http://hibernate.com </class> </hibernate-mapping> UserDetails.User" constrained="true"/> </class> </hibernate-mapping> Manager.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.0. http://javaeasytoall.hbm.xml <?xml version="1.net/hibernate-mapping-3.hibernate.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.Session.sourceforge.Configuration.lara.dtd"> <hibernate-mapping> <class name="com. import org.lara.hibernate.hibernate.cfg. import org. import org. public class Manager Lara Technologies 080-41310124 63 .java package com.

user. user. UserDetails ud = new UserDetails(). ud. Configuration config = new Configuration().com { public static void main(String[] args) { User user = new User().commit().save(user). SessionFactory sf = config. user. user.getTransaction(). user. } } Foreign key development: Lara Technologies 080-41310124 64 .setUserFirstName("MANIKANTA"). session.close(). session. config. session.configure().setAddress("TPT").beginTransaction().setUserMobileNo("9986340298").setEduc("BTech").flush().setUserEmail("manikanta@gmail. ud. ud. ud.setUserAge(23). Session session = sf. session.setUserDetails(ud). user.setDesignation("PM").com"). http://javaeasytoall.openSession(). session.setUserId("index101").buildSessionFactory(). user.setUserLastName("CHOUDHARY").setUser(user).

BATCHES table BATCH_ID is refered by so many columns from the STUDENTS TABLE hibernate. 1. cascade (optional) specifies which operations should be cascaded from the parent object to the associated object.com Usually foreign key is used for to join the two tables In this example we want to join User and UserDetails. class (optional . <on-to-one name=”” class=”” contrained=”” or cascade=””/> name: The name of the property.jdbc.0//EN" "http://hibernate.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.(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.driver.OracleDriver</property> Lara Technologies 080-41310124 65 .xml <?xml version='1. 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.Database connection settings --> <property name="connection.driver_class"> oracle. http://javaeasytoall.net/hibernate-configuration-3.dtd"> <hibernate-configuration> <session-factory> <!-.sourceforge.defaults to the property type determined by reflection): The name of the associated class.cfg.0.

hibernate.username">system</property> <property name="connection.NoCacheProvider</property> <!-.com <property name="connection. http://javaeasytoall.SQL dialect --> <property name="dialect"> org.JDBC connection pool (use the built-in) --> <property name="connection.xml"/> </session-factory> </hibernate-configuration> Student.Disable the second-level cache --> <property name="cache. public class Student { Lara Technologies 080-41310124 66 .Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.url"> jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.provider_class"> org.lara.OracleDialect</property> <!-.hbm.password">great123</property> <!-.Drop and re-create the database schema on startup --> <property name="hbm2ddl.hbm.java package com.dialect.pool_size">1</property> <!-.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.xml"/> <mapping resource="com/lara/Student.cache.auto">update</property> <mapping resource="com/lara/Batch.hibernate.

} public void setLastName(String lastName) { this. } public Integer getAge() { return age.java package com. } public String getLastName() { return lastName. private String firstName. } public Batch getBatch() { return batch.lastName = lastName. } public String getFirstName() { return firstName. } public void setFirstName(String firstName) { this. } public void setBatch(Batch batch) { this.age = age. } public void setId(Integer id) { this.lara. private String lastName. } public void setAge(Integer age) { this. Lara Technologies 080-41310124 67 .batch = batch. public Integer getId() { return id. http://javaeasytoall. private Batch batch.firstName = firstName. private Integer age. } } Batch.id = id.com private Integer id.

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

} } std. */ // Randomly UPDATE /* Batch batch = (Batch)session. } std.getStudents().setFirstName("CHANGED AGAIN MANIKANTA").load(Batch.setFirstName("CHAGED MANIKANTA").com Session session = sf. while(it.next().save(batch).next(). Iterator it = batch.openSession().getStudents(). session.saveOrUpdate(std). Student std = null.hasNext()) { std = (Student)it.INSERTION /* session.load(Batch. session. //1. Student std = null.getTransaction(). Lara Technologies 080-41310124 71 . Iterator it = batch.iterator().class.hasNext()) { std = (Student) it.getTransaction(). session.commit().class.3). */ //PARTICULAR RECORD UPDATE /* Batch batch = (Batch)session. http://javaeasytoall.getId() == 2) { break. session. if(it.beginTransaction().3).iterator().commit(). if(std.

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

} public void setStdName(String stdName) { this.Set.stdName = stdName. http://javaeasytoall. private Integer fee. public class Batch { private Integer id. } } Batch. import java. private Date startDate.Date. Lara Technologies 080-41310124 75 .batch = batch. } public void setStdQualification(String stdQualification) { this.stdQualification = stdQualification. } public Set getBatch() { return batch.id = id. } public String getStdQualification() { return stdQualification.util.HashSet. private Integer duration.util.com public void setId(Integer id) { this. private String batchName.util. private Set participents = new HashSet(). } public void setBatch(Set batch) { this. } public String getStdName() { return stdName. import java.lara. import java.java package com.

} public void setBatchName(String batchName) { this.participents = participents.id = id. Lara Technologies 080-41310124 76 .duration = duration. http://javaeasytoall. } public void addParticipentsToBatch(Student std) { participents. } public void setParticipents(Set participents) { this. } public Date getStartDate() { return startDate. } public void setId(Integer id) { this. } public Integer getDuration() { return duration. } public void setDuration(Integer duration) { this. } public String getBatchName() { return batchName.batchName = batchName. } public void setFee(Integer fee) { this. } public void setStartDate(Date startDate) { this. } public Integer getFee() { return fee.startDate = startDate.fee = fee. } public Set getParticipents() { return participents.add(std).com public Integer getId() { return id.

hbm.net/hibernate-mapping-3.dtd"> <hibernate-mapping package="com.sourceforge.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC Lara Technologies 080-41310124 77 .remove(std).getBatch().0.remove(this). http://javaeasytoall.com std.hbm.getBatch().xml <?xml version="1.add(this). } } Student.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.xml <?xml version="1. } public void removeParticipentsFromBatch(Student std) { participents.0//EN" "http://hibernate. std.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.

http://javaeasytoall.lara. import org.SessionFactory.hibernate.com "-//Hibernate/Hibernate Mapping DTD 3.Configuration.0//EN" "http://hibernate. import java.net/hibernate-mapping-3.Iterator. import org.util.sourceforge.util.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.hibernate.util. public class Manager { public static void main(String args[]) Lara Technologies 080-41310124 78 .hibernate.java package com.0. import org.cfg.Session. import java. import java.Date.dtd"> <hibernate-mapping package="com.Set.

b1.setFee(1000).addParticipentsToBatch(std).setStdName("MANIKANTA"). b2.setDuration(30).setStdQualification("B.setDuration(120). b1.Tech"). Date date = new Date().Tech"). std1. Student std = new Student(). b1.addParticipentsToBatch(std)."Changed MANIKANTA").addParticipentsToBatch(std1). Date SpringstartDay = new Date(date.setStdQualification("B. std1.com { //add(). //readBatchWiseStudents(3). Batch b2 = new Batch().setStdName("RAMESH"). b2. Student std1 = new Student(). b2.setBatchName("SPRING"). b1.setStartDate(startDay). Date startDay = new Date(date. http://javaeasytoall. } private static void add() { Batch b1 = new Batch(). std. b1.getTime() + 7*24*60*60*1000).setStartDate(SpringstartDay). b2. deletingRecord(4. std1.setId(101). std.setFee(5000).setBatchName("REGULAR JAVA").104). //UpdateParticularStudent(3.setId(4).getTime() + 10*24*60*60*1000). b1. b2. std. Lara Technologies 080-41310124 79 . b2.setId(102). b1.102.setId(3).

addParticipentsToBatch(std3).save(std). Session session = sf.configure(). std3.save(std2). } private static SessionFactory getSessionFactory() { Configuration config = new Configuration(). session.save(std3).setStdName("RAMU"). session.beginTransaction(). SessionFactory sf = getSessionFactory().save(std1).setStdQualification("Bsc").getTransaction().setId(104). session.com Student std2 = new Student(). std3. http://javaeasytoall.close().buildSessionFactory(). session. Lara Technologies 080-41310124 80 . return sf.openSession(). } private static void readBatchWiseStudents(int i) { SessionFactory sf = getSessionFactory(). b1.setId(103). Session session = sf.setStdName("NAGESH").commit(). std3. session. session. session.Tech"). session.addParticipentsToBatch(std2). session.openSession(). std2.save(b1).flush(). SessionFactory sf = config. session. std2. config. Student std3 = new Student().setStdQualification("B. b2.save(b2). std2.

if(std. } private static void UpdateParticularStudent(int batchNo.close().next().flush(). Iterator it = batch.close(). session.setStdName(modifiedName). i). http://javaeasytoall.load(Batch.flush(). session.saveOrUpdate(std).getStdName()). session. System.commit(). Session session = sf.load(Batch. Iterator allStudents = students.class.getId() == studentNo) { break. } } std. Student std = null. Batch b = (Batch)session. } session.beginTransaction(). Batch batch = (Batch)session. session. session.com session.getTransaction().getTransaction().openSession(). while(it.int studentNo.getParticipents().String modifiedName) { SessionFactory sf = getSessionFactory(). Student std = null.hasNext()) { std = (Student)allStudents.commit().getParticipents(). session.getId()+":"+std.next().iterator().out.hasNext()) { std = (Student)it.beginTransaction().iterator(). } Lara Technologies 080-41310124 81 .batchNo). Set students = b.println(std.class. session. while(allStudents.

session. Lara Technologies 080-41310124 82 .load(Batch.delete(std). session.next().remove(std).So first develop one Pojo class with all these attributes package com. Session session = sf.getParticipents(). while(it. Now create a package structure and develop a Pojo object.beginTransaction(). http://javaeasytoall. Student std = null. PERSON_AGE). session.commit(). We want to crate table for Person with column names as (Person_ID.hasNext()) { std = (Student)it. session.openSession().getTransaction(). batchNo). if(std.getParticipents(). } } batch. PERSON_NAME.int studentNo) { SessionFactory sf = getSessionFactory(). Batch batch = (Batch)session.getId() == studentNo) { break.class. session. Create one application and update the buildpath with relavent JAR files. } } Example: programaticllydeclaring properties Developing an application without configuration file.lara.iterator(). Keeping inside ur client program by creating config object.close().flush(). Iterator it = batch.com private static void deletingRecord(int batchNo.

private String personName.com public class Person { private Integer id.personAge = personAge.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3. In hbm file we want to take care about all attributes for creating table. } public int getPersonAge() { return personAge. } } Now develop one hbm file for every Pojo class in one package. } public void setPersonName(String personName) { this. } public String getPersonName() { return personName.net/hibernate-mapping-3.0. In persons table we want to make PERSON_ID column as autoincrement and primarykey then use id and generator tags. } public void setId(int id) { this.dtd"> <hibernate-mapping> Lara Technologies 080-41310124 83 . <?xml version="1. } public void setPersonAge(int personAge) { this. http://javaeasytoall.sourceforge.id = id. In hibernate with out primary key we can’t develop any table. public int getId() { return id.personName = personName. private Integer personAge.0//EN" "http://hibernate.

“system”).com <class name="com.OracleDriver”). Configuration config = new Configuration ().setProperty("dialec".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.SessionFactory. “org.cfg. public class Manager { public static void main (String [] args) { Person p1 = new Person ().setProperty("connection.setProperty("connection.password ". “thread”). “great123”). import org.setPersonAge (29).driver_class".Session. config.hibernate.hibernate. p1. “jdbc:oracle:thin:@localhost:1521:XE”). config.pool_size ". import org.setProperty("connection. “1”).dialect.hibernate.Configuration.hibernate.driver.OracleDialect”). config. config. “oracle. config.url ".setProperty("connection.setPersonName ("RAMESH").setProperty("connection. config.setProperty("current_session_context_class ". import org. p1.lara.username ". config.lara. http://javaeasytoall.jdbc. Lara Technologies 080-41310124 84 .

session.beginTransaction ().”). System.com config.openSession ().hbm. session.flush (). System.println(“transaction started. config.cache.hibernate..close ().”). System. session. session. “true”).xml”).out. SessionFactory sf = config..out. “update”).setProperty("show_sql ". System.setProperty("cache. session. “org.setProperty("hbm2ddl. System.println(“person object saved/updated.”).out.. config.println(“session got closed.println(“session got flushed. http://javaeasytoall.auto ".println(“Hibernate got configured.println(“SessionFactory got configured.e Oracle) and run the program.out.out.. System.commit ().”).addResource(“com/lara/Person. System.println(“session object got configured.getTransaction ().”). System. } } Now start the database (i.out.saveOrUpdate(p1).”).NoCacheProvider”).out.provider_class ". Session session = sf.”).buildSessionFactory ().println(“transaction committed. config.out.”). Example2 programaticllydeclaring properties Lara Technologies 080-41310124 85 .

Lara Technologies 080-41310124 86 .orderDate= orderDate. http://javaeasytoall. public Striong getOrderId() { return orderId.com create a package structure and develop a Pojo object. } public Striong getOrderDescription() { return orderDescription. private Date orderDate. } public Double getOrderPrice() { return orderPrice. } public void setOrderName (String orderName) { this. orderId= orderId. private String orderBy.lara.orderDescription = orderDescription. public class Person { private String orderId. package com.orderName = orderName. } public void setOrderDescription(int orderDescription) { this. private String orderDescription. } public String getOrderName() { return orderName. } public void setOrderDate(Date orderDate) { this. } public Date getOrderDate() { return orderDate. } public void setOrderId(int orderId) { this. private Double orderPrice. private String orderName.

com } public void setOrderPrice(int orderPrice) { this. <?xml version="1.net/hibernate-mapping-3. } public void setOrderBy(String orderBy) { this.lara.orderBy = orderBy. orderPrice = orderPrice.0//EN" "http://hibernate.0. } } Now develop one hbm file for every Pojo class in one package. http://javaeasytoall.dtd"> <hibernate-mapping> <class name="com.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 . } public String getOrderBy() { return orderBy.sourceforge.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.

username ". config.driver_class".setProperty("current_session_context_class ". “system”).out.setOredrId(“ord101”).jdbc.setProperty("connection.OracleDialect”).cfg.url ". “true”). “update”). config.SessionFactory.addResource(“com/lara/Person. public class Manager { public static void main (String [] args) { Order order= new Order(). Lara Technologies 080-41310124 88 . config.xml”).com package com. System.setProperty("connection.setProperty("connection.password ". Order.setProperty("connection.cache.setOredrBy(“LARA”). “org.lara. Order. “jdbc:oracle:thin:@localhost:1521:XE”). Order. import org.dialect.hibernate. Order. config.pool_size ". config.buildSessionFactory ().out.setProperty("cache.setProperty("connection.provider_class ".setProperty("dialec".driver. config. “great123”). import org. Configuration config = new Configuration (). Order.Configuration.setOredrName(“TV”).setOredrDate(new Date()).hibernate. config.NoCacheProvider”). SessionFactory sf = config.00). Order. http://javaeasytoall.”).”). “1”).setProperty("show_sql ". config.hibernate.println(“Hibernate got configured.hibernate. config.Session. config.setOredrDescription(“Sony TV”). “oracle.setOredrPeice(12000.hbm.auto ". import org.setProperty("hbm2ddl. config.println(“SessionFactory got configured. “thread”).hibernate.OracleDriver”). “org. System.

createCriteria(com.out. System. session.save(order). System.println(“person object saved.add(Restrictions.”).println(order. session.getOrderId()). Ctr. http://javaeasytoall.out.getOrderDescription()). for(Order order : list) { System.println(“transaction committed.out.flush ().println(order.list().”).close ().eq(“orderBy”.lara.println(“session object got configured..openSession ().createCriteria(com. System.”).beginTransaction (). System.out.com Session session = sf. abc)). System.class).println(order.out.”). System..”). session.Order.println(order.out. System.out.println(“session got closed.getOrderPrice()).getOrderDate()).println(“transaction started.Orser.getOrderBy()). session.out.println(order.”)..getTransaction ().out.out.getOrderName()).lara. } (OR) Criteria ctr = session.. System.commit ().out. System.println(order. System. } // To read all the records /* List<Order> list = session. session.println(“session got flushed.out. List<Order> For(Order order : list) { Lara Technologies 080-41310124 89 .class). System.

println(order.getOrderBy()). System. System.println(order.out.out.  when your sessionFactory object is createdthen only the table schema is creating/generating. Ctr.class).println(order.Order.createCriteria(com.println(order.lara.getOrderDate()). System.out.sqlRestriction(“orderDescription”.out.like “%h%” abc)).out.out.getOrderName()). System.getOrderDescription()). System. System.list().getOrderDate()).lara.out. System.getOrderPrice()). System.getOrderId()).println(order.println(order. List<Order> list = query.getOrderPrice()).createQuery(“from com.out.Order”). http://javaeasytoall.getOrderDescription()).println(order.println(order.println(order.getOrderId()).add(Restrictions. } */ } Now start the database (i.out. For(Order order : list) { System.println(order. System. System. Query query=session.println(order. Lara Technologies 080-41310124 90 .getOrderName()).e Oracle) and run the program.  Immaterial of calling configure by java program/xml file by the time of sessionFactory object creation time all the database related schemas are generating. } */ //same can be achieved through query /* Criteria ctr = session.getOrderBy()).out.out.println(order.com System.out.

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. 2.)  It is possible to keep more than one transaction in the same session.cfg.0//EN" "http://hibernate.sourceforge.  First-level-cahi is automatic one.it is storing the object state in the cachi and it is called as first-level cachi.xml <?xml version='1.  First-level-cachi is limited to transaction (when ever transaction is goingto commit then cachi is called. Polymorphic mappings: They are three types of polymorphi c mappings. One table per class hierarchy.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.where as in the case of saveOrUpdate(). One table per subclass.net/hibernate-configuration-3.by this we can save the network traffic. 1.  While in the case of save().0. Cachi is not available for the other transactions which is limited to one transaction. One table per concrete class.  In one transaction we can keep as many database transactions as we wish. hibernate.  For the same transaction one object is keep on changing. it is keep on calling/storing in the database. http://javaeasytoall. 3.it is calling updateQuery before commiting.dtd"> <hibernate-configuration> <session-factory> Lara Technologies 080-41310124 91 .com  Eventhough you triggered 4 times the update query on the same transaction only once is updates the query before commited.

dialect.NoCacheProvider</prope rty> <!-.provider_class">org.url">jdbc:mysql://localhost/lara</property> <property name="connection.Database connection settings --> <property name="connection.jdbc. public class Person { Lara Technologies 080-41310124 92 .JDBC connection pool (use the built-in) --> <property name="connection.SQL dialect --> <property name="dialect">org.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.xml"/> </session-factory> </hibernate-configuration> Person.Drop and re-create the database schema on startup --> <property name="hbm2ddl.driver_class">com.Disable the second-level cache --> <property name="cache.username">root</property> <property name="connection.Driver</property> <property name="connection.com <!-.java package com.auto">update</property> <mapping resource="com/lara/Person.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.mysql.MySQLDialect</property> <!-.password"></property> <!-.hbm.pool_size">1</property> <!-. http://javaeasytoall.hibernate.hibernate.cache.lara.

java package com. } public void setEmpNo(String empNo) { this.id = id. } } Employee. public String getEmpNo() { return empNo.firstName = firstName. } public void setFirstName(String firstName) { this.lara. public class Employee extends Person { private String empNo. http://javaeasytoall. private String firstName.com private int id.empNo = empNo.lara.java package com. } } PermanentEmployee. } public void setId(int id) { this. public int getId() { return id. public class PermanentEmployee extends Employee { Lara Technologies 080-41310124 93 . } public String getFirstName() { return firstName.

net/hibernate-mapping-3.0//EN" "http://hibernate.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. Lara Technologies 080-41310124 94 .com private Double allowances. http://javaeasytoall. } } Person.0.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3. public Double getAllowances() { return allowances.allowances = allowances.xml <?xml version="1.dtd"> <hibernate-mapping package="com.sourceforge.lara.hbm. } public void setAllowances(Double allowances) { this.java package com.

xml Person. config.save(pe).dtd"> <hibernate-mapping package="com. session.0. Configuration config = new Configuration(). SessionFactory sf = config.hibernate. pe.com import org.close().setAllowances(50000.hbm. import org.0//EN" "http://hibernate. } } 2) One table per subclass: For every subclass there is one table In above example just change the Person. public class Manager { public static void main(String[] args) { PermanentEmployee pe = new PermanentEmployee().commit().openSession().Configuration.00).beginTransaction().buildSessionFactory().cfg.getTransaction(). pe. Session session = sf. session.net/hibernate-mapping-3.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.sourceforge.xml <?xml version="1. session. session. import org.setId(1). session. http://javaeasytoall.lara"> Lara Technologies 080-41310124 95 .hbm.Session.configure().SessionFactory.hibernate.flush().hibernate.

0//EN" "http://hibernate.Driver</property> <property name="connection.cfg.mysql.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.Database connection settings --> <property name="connection.url">jdbc:mysql://localhost/lara</property> <property name="connection.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.jdbc.sourceforge.xml <?xml version='1. Example for Query interface: hibernate.username">root</property> Lara Technologies 080-41310124 96 .net/hibernate-configuration-3.dtd"> <hibernate-configuration> <session-factory> <!-.0.driver_class">com. http://javaeasytoall.

Lara Technologies 080-41310124 97 .java package com.password"></property> <!-. public class Person { private String id.hibernate.JDBC connection pool (use the built-in) --> <property name="connection.dialect.NoCacheProvider</prope rty> <!-.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.cache.auto">update</property> <mapping resource="com/lara/Person.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.SQL dialect --> <property name="dialect">org.Disable the second-level cache --> <property name="cache.lara. http://javaeasytoall.hbm.provider_class">org.com <property name="connection.MySQLDialect</property> <!-.xml"/> </session-factory> </hibernate-configuration> Person.pool_size">1</property> <!-.hibernate.Drop and re-create the database schema on startup --> <property name="hbm2ddl.

} } Person. http://javaeasytoall. } public String getLastName() { return lastName. } public void setLastName(String lastName) { this.Person" table="PERSONS"> Lara Technologies 080-41310124 98 .0.sourceforge. } public String getFirstName() { return firstName.personAge = personAge.lastName = lastName.xml <?xml version="1. } public void setPersonAge(Integer personAge) { this. } public void setFirstName(String firstName) { this.lara. } public void setId(String id) { this.id = id.0//EN" "http://hibernate.hbm.com private String firstName.firstName = firstName.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3. private String lastName.net/hibernate-mapping-3. public String getId() { return id. } public Integer getPersonAge() { return personAge.dtd"> <hibernate-mapping> <class name="com. private Integer personAge.

p1.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. p1. import org.hibernate.Query.setFirstName("MANI"). p1. http://javaeasytoall. config. SessionFactory sf = config.Session. Session session = sf.setPersonAge(23).hibernate.java package com.configure().beginTransaction().List.createQuery("from com. session.cfg. import org.setId("INDEX104"). public class Manager{ public static void main(String[] args) { /* Person p1 = new Person().SessionFactory.lara. List<Person> list = query. import org. */ Configuration config = new Configuration().Configuration.buildSessionFactory().hibernate.list(). Query query = session. p1.Person"). import java.setLastName("KANTA").util.openSession().hibernate.lara. import org. for(Person p:list) { Lara Technologies 080-41310124 99 .

save(p1).out.getPersonAge()). session.sourceforge.0.0//EN" "http://hibernate.Database connection settings --> <property name="connection.net/hibernate-configuration-3.password">great123</property> <!-. } } 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().cfg.JDBC connection pool (use the built-in) --> <property name="connection. EG: hibernate.getTransaction().url"> jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.driver. session.getId()+":"+p.dtd"> <hibernate-configuration> <session-factory> <!-.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3. } //session.println(p.close().username">system</property> <property name="connection.jdbc.OracleDriver</property> <property name="connection.pool_size">1</property> Lara Technologies 080-41310124 100 .commit(). session.xml <?xml version='1.flush().getFirstName() +":"+p.driver_class"> oracle. http://javaeasytoall.com System.

hibernate.com <!-..OracleDialect</property> <!-.xml"/> </session-factory> </hibernate-configuration> Person.pkField = pkField.lara.Disable the second-level cache --> <property name="cache.provider_class"> org.cache.NoCacheProvider</property> <!-. private Integer personAge.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-.hibernate. } Lara Technologies 080-41310124 101 .auto">update</property> <mapping resource="com/lara/Person. public class Person { private PKField pkField.SQL dialect --> <property name="dialect"> org. } public void setPkField(PKField pkField) { this.Drop and re-create the database schema on startup --> <property name="hbm2ddl. http://javaeasytoall. private String lastName.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.hbm. public PKField getPkField() { return pkField.dialect.java package com.

} public void setPersonAge(Integer personAge) { this. } public Integer getPersonAge() { return personAge.firstName = firstName. http://javaeasytoall. } public boolean equals(Object obj) { Lara Technologies 080-41310124 102 . private String firstName.Serializable.id = id. } public void setLastName(String lastName) { this. } public void setFirstName(String firstName) { this. public class PKField implements Serializable { private String id. } public String getFirstName() { return firstName.personAge = personAge. } } PKField.lastName = lastName. } public void setId(String id) { this. public String getId() { return id.io.com public String getLastName() { return lastName.java package com.lara. import java.

List.net/hibernate-mapping-3.hashCode()+firstName.0. } public int hashCode() { return id.hibernate.lara. import java.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.com PKField pk = (PKField)obj. Lara Technologies 080-41310124 103 .0//EN" "http://hibernate.util.Session.Query.firstName). import java. http://javaeasytoall.xml <?xml version="1.Iterator.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.hibernate. import org.hashCode().util. } } Person.hbm.java package com.dtd"> <hibernate-mapping package="com.equals(pk.equals(pk. return id.id)&& firstName.sourceforge. import org.

System.openSession(). p1.setId("INDEX102"). String hql = "form com.age=?". Query query = session.configure(). public class Manager { public static void main(String[] args) { /* Person p1 = new Person().SessionFactory. PKField pk = new PKField(). Session session = sf. query.next().Person p where p. SessionFactory sf = config. pk.setPersonAge(29).println(p.save(p1). config.getPkField().setFirstName("MANI"). Lara Technologies 080-41310124 104 .createQuery(hql). import org.hasNext()) { Person p = it. p1.getFirstName()). session.lara. */ Configuration config = new Configuration().setString(0.setLastName("CHOUDHARY"). while(it.hibernate.buildSessionFactory().hibernate. pk.iterate(). p1. "29").com import org. http://javaeasytoall. Iterator<Person> it = query.beginTransaction().Configuration.cfg. } //session.out.setPkField(pk).

System.getTransaction(). Pk.getPersonAge()). System.out.class. */ /* // To get all records List<Person> list=session.commit().getFirstName()).println(p2.setFirstName(“abc”). System.println(p2. /* // To read a record PKField pk1 = new PKField(). session.lara.out.setId (101).Person.setFirstName(“abc”).createCriteria (com. PKField ().println(p2. Pk. System.out.load(com.println(p2. Person p2= (Person)session.println(p2.out.println(p2. } */ /* // To update one record PKField pk1 = new PKField().class.setId (101). Lara Technologies 080-41310124 105 .getId()). Pk.getLastName()). System.lara.pk1).getFirstName()).out. Pk. PKField ().getLastName()). session. System.flush(). http://javaeasytoall.println(p2.println(p2.out.out.close(). PKField ().com session.out.getPersonAge()).Person. System.getId()). list) For(Person p1 : list) { System. PKField ().

1).setAge(6).setLastName(“Tecnologies”).com Person p2=(Person)session. */ } } Lara Technologies 080-41310124 106 . P2.setAge(6).Person.class.class. P2. */ /* // To delete one record PKField pk1 = new PKField(). 1).setLastName(“Tecnologies”). Person p2=(Person)session.load(com. Session. Session. P2. P2. http://javaeasytoall.setFirstName(“LARA”). Pk.lara.setId (101). P2. P2.delete(p2).lara.load(com.setFirstName(“LARA”). Pk.Person.setFirstName(“abc”).saveOrUpdate(p2).

as well as some example usages. One of these new ease-of-development features in JDK5 are annotations. Quoting from Sun's official site. constructors. Annotations are like meta-tags that you can add to your code and apply them to package declarations. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it.com Java Annotations The objective of changing older JDK versions to JDK5 largely centered on enhancing ease-of-development. and so on. it becomes easier to maintain. and variables. 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. type declarations. The resulting codes are also less likely to be bug- prone. parameters. whether they are incomplete." Simply speaking. As a result. their benefits. In other words. Annotation-based development is certainly one of the latest Java development trends. whether your classes have references to other classes. http://javaeasytoall. "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. the new features shift the responsibility for writing the boilerplate code from the programmer to the compiler. you will have helpful ways to indicate whether your methods are dependent on other methods. methods. Annotation-based development relieves Java developers from the pain of cumbersome configuration. If the source code is boilerplate free. The Basics Lara Technologies 080-41310124 107 . I'll describe some basics of annotation. fields.

http://javaeasytoall. } Example to Annotate Your Code (Annotation) MyAnnotation (doSomething="What to do") public void mymethod() { . Example: public @interface MyAnnotation { } Lara Technologies 080-41310124 108 . and the annotation is the specific usage of that type. followed by the annotation type. followed by the interface keyword plus the annotation name. An example of each can be seen below: Example to Define an Annotation (Annotation type) public @interface MyAnnotation { String doSomething(). One is the "annotation" itself. you can put data within parenthesis after the annotation name.. The type is the actual construct used." An annotation is the meta-tag that you will use in your code to give it some life. On the other hand.. Additionally. except the annotation name itself. An annotation type definition takes an "at" (@) sign.com There are two things you need to consider with annotations. Annotation type is used for defining an annotation. an annotation takes the form of an "at" sign (@). } Annotation Types There are three annotation types:  Marker: Marker type annotations have no elements. This is simplest form of annotation.. You will use it when you want to create your own custom annotation. another is the "annotation type.

} Usage: @MyAnnotation ("What to do") public void mymethod() { ... This can be represented with a data=value pair or.com Usage: @MyAnnotation public void mymethod() { . annotations provide a single piece of data only. String date().. Therefore. Example: public @interface MyAnnotation { String doSomething(). you must use a full data=value parameter syntax for each member. or single-value type. http://javaeasytoall. } Usage: Lara Technologies 080-41310124 109 ... }  Full-value or multi-value: Full-value type annotations have multiple data members. Example: public @interface MyAnnotation { String doSomething(). int count. }  Single-Element: Single-element. simply with the value (a shortcut syntax) only. within parenthesis..

Lara Technologies 080-41310124 110 . following with an interface keyword. following with the annotation name. 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.  Meta annotations: These are the annotation types designed for annotating annotation-type declarations. date="09-09-2005") public void mymethod() { . 4.com @MyAnnotation (doSomething="What to do". } Rules of Thumb for Defining Annotation Type Here are some rules-of-thumb when defining an annotation type: 1. 3. Simply speaking.. Method declarations should not have any throws clauses. 2. count=1.. which you can use to annotate your code only. these are called the annotations-of- annotations.. Method declarations should not have any parameters. http://javaeasytoall. Annotation declaration should start with an 'at' sign like @. you cannot use those to create a custom annotation type.

They are:  Override  Deprecated  Suppresswarnings It's important to note that JDK5 (in other words. Tiger) actually does not have many built-in annotations. Example 1 demonstrates the override annotation: Example 1 public class Test_Override { @Override public String toString() { return super. The Override annotation An override annotation indicates that the annotated method is required to override a method in a super class. it allows core Java the ability to support the annotation feature.toString() + " Testing annotation name: 'Override'". If a method with this annotation does not override its super- class's method. the compiler will generate an error. along with examples.com Simple Annotations There are only three types of simple annotations provided by JDK5. The charter for JSR-175 strictly dictated it was to define a metadata facility. http://javaeasytoall. The following sections will describe each simple annotation in more depth. } } Lara Technologies 080-41310124 111 . rather. It was left to the programmers to write custom annotation types and to other JSRs to write a set of standard annotation types.

Example 2 shows you the deprecated annotation. } } Next.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. Example 2 First. 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 .out.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. create a class with the deprecated method as follows: public class Test_Deprecated { @Deprecated public void doSomething() { System. you will get something like the following: Compiling 1 source file to D:tempNew Folder (2) TestJavaApplication1buildclasses D:tempNew Folder (2)TestJavaApplication1srctest myannotationTest_Override.println("Testing annotation name: 'Deprecated'"). the compiler should warn you about it. http://javaeasytoall.

But. you will see something like this: Compiling 1 source file to D:tempNew Folder (2)TestJavaApplication1buildclasses D:tempNew Folder (2)TestJavaApplication1srctestmyannotation TestAnnotations. both warnings will be suppressed at the method level only. if you annotate a class to suppress one warning and one of its methods to suppress another warning. As an example. t2. See Example 3 for the suppresswarnings annotation. } The doSomething() method in this example is declared as a deprecated method. 1 warning The Suppresswarnings annotation This annotation indicates that compiler warnings should be shielded in the annotated element and all of its sub- elements. if you try to compile TestAnnotations.java where the deprecated method is used. Example 3 public class TestAnnotations { public static void main(String arg[]) throws Exception { Lara Technologies 080-41310124 113 .doSomething(). this method should not be used when this class is instantiated by other classes. no warning messages will be generated by the compiler.myannotation.java.doSomething(). http://javaeasytoall. Therefore.java:27: warning: [deprecation] doSomething() in test. The set of warnings suppressed in an element is the superset of the warnings in all of its containing sub- elements.com public TestAnnotations() { Test_Deprecated t2=new Test_Deprecated(). If you compile Test_Deprecated.Test_Deprecated has been deprecated t2.

Note: It is a good idea to use this annotation at the most deeply nested element where it is effective. contain four types.FIELD)—can be applied to a field or property Lara Technologies 080-41310124 114 . Therefore. It contains the following enumerated types as its value:  @Target(ElementType. } } In this example.TYPE)—can be applied to any element of a class  @Target(ElementType.com new TestAnnotations(). 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. you are suppressing the deprecation warning for the method listing shown in Example 2. Meta-Annotations (Annotation Types) Meta-annotations. you should annotate that method rather than its class. which are actually known as the annotations of annotations. http://javaeasytoall. Because the method is suppressed. you are unlikely to view the "deprecation" warning any more.doSomeTestNow(). t2. if you want to suppress a warning in a particular method.doSomething(). } @SuppressWarnings({"deprecation"}) public void doSomeTestNow() { Test_Deprecated t2 = new Test_Deprecated().

METHOD)—can be applied to a method level annotation  @Target(ElementType. http://javaeasytoall.printf("Testing Target annotation").CONSTRUCTOR)—can be applied to constructors  @Target(ElementType. as follows: @Target(ElementType. create a class that will use the Test_Target annotation: public class TestAnnotations { public static void main(String arg[]) { new TestAnnotations().LOCAL_VARIABLE)—can be applied to local variables  @Target(ElementType.com  @Target(ElementType.out. } @Test_Target(doTestTarget="Hello World !") public void doTestTarget() { System.PARAMETER)—can be applied to the parameters of a method  @Target(ElementType. } Next.doTestTarget().METHOD) indicates that this annotation type can be used to annotate only at the method Lara Technologies 080-41310124 115 . } } The @Target(ElementType.METHOD) public @interface Test_Target { public String doTestTarget(). define an annotation named Test_Target with @Target metadata.ANNOTATION_TYPE)—indicates that the declared type itself is an annotation type Example 4 demonstrates the target annotation: Example 4 First.

public static void main(String arg[]) { new TestAnnotations(). If you compile the preceding code.doTestTarget(). if you declare a String variable and apply your newly created annotation.com levels. no warning messages will be shown. Because you have defined your annotation @Test_Target to be applicable only at method- level. } } The only change you can see from above is that the annotation declaration is shifted from method-level to field- level. There are three values: Lara Technologies 080-41310124 116 . what will happen? Let me demonstrate this as follows: public class TestAnnotations { @Test_Target(doTestTarget="Hello World !") private String str. } public void doTestTarget() { System. you are likely to get something like this: "TestAnnotations. http://javaeasytoall.out.java:16: annotation type not applicable to this kind of declaration at line 16.java": D:R_AND_DTestAnnotationsrctestmyannotation TestAnnotations. Now. which is not correct.printf("Testing Target annotation"). 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. if you try to compile this class.

} In this example.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. Example 6 demonstrates using @Documented further: Example 6 @Documented public @interface Test_Documented { String doTestDocument(). 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.CLASS—Annotations with this type will be by retained by the compiler at compile time.SOURCE—Annotations with this type will be by retained only at the source level and will be ignored by the compiler  RetentionPolicy. But if @Documented is used.com  RetentionPolicy. the @Retention(RetentionPolicy.RUNTIME value in action: Example 5 @Retention(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) public @interface Test_Retention { String doTestRetention(). but will be ignored by the VM  RetentionPolicy. } Lara Technologies 080-41310124 117 . http://javaeasytoall. it then will be processed by javadoc- like tools and the annotation type information will also be included in the generated document.

Lara Technologies 080-41310124 118 .doSomeTestRetention(). } @Test_Retention (doTestRetention="Hello retention test") public void doSomeTestRetention() { System. new TestAnnotations(). } @Test_Documented(doTestDocument="Hello document") public void doSomeTestDocumented() { System.printf("Testing annotation 'Retention'"). } } Now. you will see something like Figure 1.printf("Testing annotation 'Documented'"). if you run the javadoc command and view the generated TestAnnotations. update your TestAnnotations class as follows: public class TestAnnotations { public static void main(String arg[]) { new TestAnnotations().com Next. http://javaeasytoall.out.html file.doSomeTestDocumented().out.

com Figure 1 As you can see from the screenshot. this description is provided for the doSomeTestDocumented() method. The Inherited annotation This is a bit of a complex annotation type. there is no annotation- type information for the doSomeTestRetention() method. if you define an annotation with the Lara Technologies 080-41310124 119 . This is because of the @Documented tag attached with your Test_Documented annotation. It indicates that the annotated class with this type is automatically inherited. http://javaeasytoall. Your earlier annotation Test_Retention did not include this tag. More specifically. But.

} Lara Technologies 080-41310124 120 . String doSomething() default "Do what?". and finally extend the class in a subclass. 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. http://javaeasytoall. } Next. all properties of the parent class will be inherited into its subclass. you will get an idea about the benefits of using the @Inherited tag. These are automatically inherited because of using the @Inherited tag. you do not have to define the interface methods inside the implementing class. then annotate a class with your annotation. } public String doSomething() { return "". annotate a class with your annotation: @myParentObject public Class myChildObject { } As you can see. With Example 7. define your annotation: @Inherited public @interface myParentObject { boolean isInherited() default true. Example 7 First. } public boolean equals(Object obj) { return false.com @Inherited tag.

com public int hashCode() { return 0. Lara Technologies 080-41310124 121 . you will have to implement the equals(). toString().Annotation class. It does not matter whether you want to implement these methods or not. and hasCode() methods of java.lang. you will have to include these in your inherited object.lang. } public Class annotationType() { return null. } public String toString() { return "". Besides the isInherited() and doSomething() methods from myParentObject.Object and also the annotationType() method of java. http://javaeasytoall. } } Do you see the difference? You can see that you will have to implement all the methods that the parent interface owns.annotation.

Annotations provide data about a program that is not part of the program itself. There are 2 things u need to consider with annotations they are: 1. 2. Single-Element: provides a single piece of data only. Full-value or Multi-value: it is having multiple data members.fields. There are three types of Annotations they are: 1. Annotations can be applied to a program’s declarations of a classes.except the annotation name itself.0. Uses of Annotations are: 1. It is specific usage of that type.they have no direct effect on the operation of the annotate. 3. It is actual construct used. This can be represented with a data=value pair or. Run-time prucessing: sone Annotations are available to be examined at runtime. 2. http://javaeasytoall. The Annotation appears first.XML files and so on. Lara Technologies 080-41310124 122 . simply with the value only within the peranthasis. Marker: this type have no elements.com Using Annotations in Hibernate: Annotation is for providing meta information. It is introduced in jdk5. and may include elements with named or unnamed values. Compiler-time and deployment-time processing: Software tools can process annotation information to generate code . 2. annotation: the mega data that u will use in ur code to give it some life. methods and other elements. annotation-type: is used for defining an annotation. Information for the compiler: Annotations can be used by the compiler to delete errors or supress warnings. often on its own line. we must use a full data=value parameter systax for each member. 3.

we can use Annotations instead of providing documentation and comments.it will act as a member as like class. through target we can able to fix to classes/packages/methods.interface.type/method/parameter …etc. annotation can be used for classes/packages/methods. we can fix annatations to classes/interface/methods.Examle: Public class Test { @Override Public String tostring() { Return string. we can write through anotations. It is overriden method it is not your own method @Target: Annotations can be used in any of the place by defining target. } } @Override: indicates that annotation which provides meta information to that tostring(). 5.interface. Lara Technologies 080-41310124 123 .com Instead of writing hbm file we can keep that information. 2. methods should not take any parameter and should not throw any exceptional class. 4. annotation contains only method definitions. The rules for developing an annotation: 1. 3. if target is field. 7. http://javaeasytoall.) @Depricated: we can supress the depricated methods. we can fix annatations to classes/interface/methods . 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. if target is type. 6. enum etc. Need to fix the target to where to use that Example:@target(ElementType. Annotation is also getting a .anotations mainly to give.class file as like class.

) @Documented: when ever you are using this annotation that .java file java documentation method is available.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. hibernate-3.(it also should be documented.) To use annotation for providing mapping information without hbm file in the hibernate. ejb3.3.out.0-persistance.class/runtime/source/… etc. } Lara Technologies 080-41310124 124 .0. http://javaeasytoall. sringframework-2.jar and dependent jar files. 2. Exaple: @retention(RetentionPolicy. A1.jar(must and should) examlpe1: class A { @diprecated String test() { System. } } Class Manager { Public static void main(String args[]) { A a1=new A().”).4 with dependencies(relavent JAR files). 4. For that update the buildpath with 4 types of JAR files they are: 1. Oracle 4th type Driver JAR file 3.2. To avoid mapping resource inside hibernate-mapping tag.test().println(“Dipricated method.

List. } } Developing our own Annotation: public @interface HelloAnnotation { String hello(). } class Test Lara Technologies 080-41310124 125 .com } Examle2: Class Test { @suppresswarnings(“unchecked”) Public static void main(String args[]) { ArrayList list=new ArrayList(). } class A { @HelloAnnotation(hello=”welcome to all.”) } class B extends A { } public @interface TestAnnotation { int count().add(10). String date(). http://javaeasytoall.

persistance.lara.entity. http://javaeasytoall.persistance. date=02-02-2009) } Example: hibernate programe with usage of annotations. public int getPersonId() { return personId.jable. } public String getPersonName() { return personName.com { @TestAnnotation(count=100. Lara Technologies 080-41310124 126 .personName = personName.column. @column(name=”person_name”) privateString personName.persistance. import javax. } public void setPersonName(String personName) { this. import javax. import javax. import javax.Id.persistance. } } package com. @Entity @Table(name=”Person”) public class Person { @Id @column(name=”person_id”) private int personId.personId = personId. } public void setPersonId(String personId) { this.

openSession().com public class Manager { Public static void main(String args[]) { Person p1=new person(). } } Lara Technologies 080-41310124 127 . sessionFactory sf=ac.buildSessionFactory().setPersonId(1010).save(p1).close(). P1.beginTransaction().flush().commit().setPersonName(“UDAY ”). AnotationConfiguration ac=new AnotationConfiguration(). Session. P1. Session. ac.getTransaction. Session. Session. Session session=sf.configure(). http://javaeasytoall. Session.

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

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.com i. And the association between objects is supported by the persistence mechanism. Light Object Mapping: The entities are represented as classes that are mapped manually to the relational tables. or applications with common. Medium Object Mapping: The application is designed around an object model. This is best suited for medium-sized applications with some complex transactions. This approach is successful for applications with a less number of entities. Apart from this. ii. including the UI is designed around the relational model and SQL based relational operation. iv. The persistence layer implements transparent persistence: persistent classes do not inherit any special base class or have to implement or special interface. and queries are specified using an object-oriented expression language. inheritance. metadata-driven data models. Used when the mapping exceed 25 different database products at a time. Efficient fetching strategies and caching strategies are implemented transparently to the application. iii. Pure relational: The entire application. The code is hidden from the business logic using specific design patterns. Full Object Mapping Full Object Mapping supports sophisticated object modeling: composition. This approach is most known to all. http://javaeasytoall. The SQL code is generated at build time. ORM provides following benefits:  Improved productivity Lara Technologies 080-41310124 131 . polymorphism and persistence.

Maintainability – As hibernate provides most of the functionality. ii. But in hibernate. Out of which the following are the most important one. iii. Vendor independence – Irrespective of the different types of databases that are there. iv. Performance – Hand-coded persistence provided greater performance than automated one. http://javaeasytoall. Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.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. If it is automated persistence then it still increases the performance. the LOC for the application will be reduced and it is easy to maintain. it provides more optimization that works all the time there by increasing the performance. 6) What is Hibernate? Hibernate is powerful. But this is not true all the times. By automated object/relational persistence it even reduces the LOC. high performance object/relational persistence and query service. hibernate provides a much easier way to develop a cross platform application. Hibernate lets developers develop persistent class following Lara Technologies 080-41310124 132 . i.

Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. does not depend on any database. but don’t use id if the id field is surrogate key 3. 7) What are the benefits of ORM and Hibernate?  Productivity: Hibernate provides much of the functionality. 8) What are the best practices for Hibernate? 1. 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.com object-oriented principles such as association. Persistence class should not be final. 4. polymorphism. composition and collections. Implement equals() and hashCode(). inheritance. so developers focuses on business logic  Maintainability: LOC is very less  Performance: Automated persistence works fast  Vendor Independence: Easier for cross platform. useful when migrating to multi- processor cluster. Implement serializable interface. Lara Technologies 080-41310124 133 . http://javaeasytoall. Use JavaBeans 2.

com 9) Show Hibernate overview? ` 10) What are the advantages of Hibernate over jdbc? Hibernate Vs. 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. JDBC :- JDBC Hibernate With JDBC.

http://javaeasytoall. number of queries to perform same It also selects an effective way to task. 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.com database tables. i. 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. 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. Hibernate to select effective query from a also supports native SQL statements. code for this. RDBMS. As in XML files. 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. With JDBC. The code written to Hibernate provides this mapping map table data to application objects itself. 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.e. Application using JDBC to handle persistent data (database tables) having database specific code in large amount. for polymorphic queries. programmer from manual handling of Lara Technologies 080-41310124 135 . The actual mapping between and vice versa is actually to map tables and application objects is done table fields to object properties. structure as well as to change code written to map table-to-object/object- to-table. It relieves data in application. So with JDBC. perform a database manipulation task for an application. Hibernate provides transparent With JDBC.

cost. caching is maintained by performance if client application hand-coding. hence reducing the mapping between Java objects and development time and maintenance database tables is done manually. reads same data many times for same write. database. version is automatically updated for this tuple by Hibernate. http://javaeasytoall. 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. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. 11)What are POJOs? POJO stands for Plain Old Java Objects. Besides they can also have some business logic related Lara Technologies 080-41310124 136 . cache is set to application work space. with Transparent Persistence. same tuple and then modify it and This check has to be added by the one user save this modified tuple to developer. 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.com persistent data. It improves With JDBC. Hibernate. So if two users retrieve always every user has updated data. Relational tuples are moved to this cache as a result of query. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.

12) What is object/relational mapping metadata? ORM tools require a metadata format for the application to specify the mapping between classes and tables. Typical mapping file look as follows: Lara Technologies 080-41310124 137 . This is just a convention and it’s not mandatory.com to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.hbm. http://javaeasytoall. The extension of these files should be “. 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.hbm. Java types and SQL types. properties and columns.xml The filename varies here. associations and foreign keys.xml”. This information is called the object/relational mapping metadata. 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. It defines the transformation between the different data type systems and relationship representations. But this is the best practice to follow this extension.

com 16) What are the important tags of hibernate. http://javaeasytoall.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 .

xml (or hibernate.e.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. • Mapping files (*.hbm.properties file. 18) How will you configure Hibernate? The configuration files hibernate.xml.xml are used by the Configuration class to create (i. If both files are present in the classpath then hibernate. security levels and all are defined.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.properties): These two files are used to configure the hibernate sevice (connection driver class.hbm. connection URL.xml file overrides the settings found in the hibernate. Weblogic and WebSphere. configure and bootstrap hibernate) the SessionFactory.properties) and mapping files *. • hibernate.xml (alternatively can use hibernate. An example of this kind of environment is environment provided by application servers such as JBoss.cfg. i. connection username.cfg. Non-managed environment – This kind of environment provides a basic configuration template.cfg. Tomcat is one of the best examples that provide this kind of environment. 19) What are the most common methods of Hibernate configuration? Lara Technologies 080-41310124 139 .hbm.com There are mainly two types of environments in which the configuration of hibernate application differs.xml files. which in turn creates the Session instances. ii. Session instances are the primary interface for the persistence service. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *. For example Account.hbm. transaction boundaries. dialect etc). http://javaeasytoall.class will have a mapping file named Account. connection password. Managed environment – In this kind of environment everything from database connections.

lang.User" table="user"> <property column="USER_NAME" length="255" name="userName" not-null="true" type="java. where we map java class to table and database columns to Java class variables.String"/> </class> </hibernate-mapping> 23) What are the different methods of identifying an object? Lara Technologies 080-41310124 140 .addResource("myinstance/MyConfig.xml") . Example : <hibernate-mapping> <class name="com. SessionFactory sessions = new Configuration() . 22) How do you map Java Objects with Database tables?  First we need to write Java domain objects (beans with setter and getter). This is less readable when compared to actual java code.String"/> <property column="USER_PASSWORD" length="255" name="userPassword" not-null="true" type="java. http://javaeasytoall. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining.cfg.xml. The variables should be same as database columns.lang.  Write hbm.buildSessionFactory().setProperties( System.getProperties() ) .com The most common methods of Hibernate configuration are:  Programmatic configuration XML configuration (hibernate.test.hbm.xml) 20) What is meant by Method chaining? Method chaining is a programming technique that is supported by many hibernate interfaces.

com There are three methods by which an object can be identified. Database identity – Objects stored in a relational database are identical if they represent the same row or. Object equality – Objects are equal if they have the same value.lang. ii. This can be checked by using the = = operator. share the same table and primary key value.AMOUNT) from BID b where b. iii. Classes that don’t explicitly override this method inherit the implementation defined by java. i.ITEM_ID = ITEM_ID )" type="big_decimal"/>  Typical and most common property mapping Lara Technologies 080-41310124 141 . equivalently. http://javaeasytoall. as defined by the equals( ) method. which compares object identity. Object identity –Objects are identical if they reside in the same memory location in the JVM. 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.Object.

These interfaces are called as Extension interfaces.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.  ProxyFactory interface . saved or deleted. Like when an object is loaded. 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. but they’re useful for implementing certain kinds of generic functionality. 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. Lara Technologies 080-41310124 142 . There is no need to implement callbacks in hibernate applications. 27) What are the Extension interfaces that are there in hibernate? There are many extension interfaces provided by hibernate.

Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads. i. iii. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. iv. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution. JTA transaction. 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. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction. The instances of this interface are lightweight and are inexpensive to create and destroy. ii. http://javaeasytoall. v. Out of which the following are the most important one. Hibernate sessions are not thread safe. 29) what is SessionFactory? Lara Technologies 080-41310124 143 . Session Interface – This is the primary interface used by hibernate applications. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application.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.

short-lived object representing a conversation between the application and the persistent Store. cfg.com SessionFactory is an interface from which the application gets Session instances. short-lived object representing a conversation between the application and the persistent store. Typically one instance of SessionFactory at startup is created for the whole application.hbm. SessionFactory caches generate SQL statements and other mapping metadata that hibernate uses at runtime. we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. 31) Is SessionFactory a thread safe object? Yes. It allows you to create query objects to retrieve persistent objects. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory(). It represents a persistence manager that manages operations like storing and retrieving objects from database. Lara Technologies 080-41310124 144 .buildSessionFactory().setProperties( System. SessionFactory is a threadsafe.addResource("myinstance/MyConfig.xml"). SessionFactory sessions = cfg. It is a single-threaded. Instances of sessions are inexpensive to create and destroy.getProperties() ). 30) How do you create a SessionFactory? Configuration cfg = new Configuration(). so many threads can request for session and immutable cache of compiled mappings for a single database. cfg. Sessions are opened by SessionFactory and closed when all the work is complete. 32) What is session? Session is a lightweight and non thread safe object that represents a single- unit-of-work with the database. A single-threaded. http://javaeasytoall. First. 33) What role does the Session interface play in Hibernate? The Session interface is the primary interface used by Hibernate applications.

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. 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.com Session session = sessionFactory.openSession(). The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. http://javaeasytoall. 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. There is typically a single SessionFactory for the whole application—created during application initialization.buildSessionFactory(). 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 . 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.

hibernate.PostgreSQLDialect 41). hibernate.transaction. 40) What does hibernate.connection.hibernate. 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.properties file consist of? This is a property file that should be placed in application class path. http://javaeasytoall.transaction.transaction.dialect. may not be updated or deleted by the application.properties file.sf. transient object. and persistent object? Transient Objects: Lara Technologies 080-41310124 146 . hibernate is first initialized.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.hibernate.dialect = net.JBossTransactionManagerLookup hibernate.datasource = java:/comp/env/jdbc/AuctionDB hibernate.sf. Immutable classes. This feature is called transactional write-behind. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.factory_class = net. 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.sf.JTATransactionFactory hibernate. So when the Configuration object is created.manager_lookup_class = net.. What are detached objects. At this moment the application will automatically detect and read this hibernate.transaction.

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. Hibernate will generate appropriate hql queries based on the dialect defined.com Transient Objects are the objects or instances of persistent classes that are not currently in session. 44) If you want to see the Hibernate generated SQL statements on console. 42) How does Hibernate distinguish between transient and detached objects? Hibernate uses the version property if there exist one or uses identifier value. http://javaeasytoall. what should we do? Lara Technologies 080-41310124 147 . Persistent Object: Persistent Object is the object that is in session currently. Cons: Working with detached objects is quite cumbersome and using Data Transfer Object for the presentation layers is better than using detached 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. we can switch databases. It has a representation in the database and an identifier value and might have been saved or loaded. 43) How do you switch between relational databases without code changes? Using Hibernate SQL Dialects .

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. It also allows the user to express in native SQL. Example:- <id column="USER_ID" name="id" type="java. A theta-style join in the WHERE clause. store. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. update. the Hibernate query Language (HQL). and retrieve objects from a database. Answer 2 : Hibernate offers a query language that embodies a very powerful and flexible mechanism to query. 48) Explain Criteria API Lara Technologies 080-41310124 148 . http://javaeasytoall.Long"> <generator class="sequence"> <param name="table">SEQUENCE_NAME</param> <generator> </id> 46) What is HQL? HQL stands for Hibernate Query Language. This language.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. is an object-oriented extension to SQL.lang.

EMP_ADDRESS AS {emp.com Criteria is a simplified API for retrieving entities by composing Criterion objects.list(). Example: <sql-query name = "empdetails"> <return alias="emp" class="com. "Boston")) . "a%") ) . emp.EMP_ID AS {emp.NAME LIKE :name </sql-query> Invoke Named Query : List people = session. 49) What do you mean by Named – SQL query? Named SQL queries are defined in the mapping xml document and called wherever required.like("address".address}.add(Restrictions. emp.add(Restrictions.createCriteria(Employee.asc("name") ) .like("name". http://javaeasytoall.setMaxResults(50) . 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.setString("TomBrady".Employee"/> SELECT emp. 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 .getNamedQuery("empdetails") .empid}. Example : List employees = session.EMP_NAME AS {emp.class) .test.list().name} FROM Employee EMP WHERE emp. name) .addOrder(Order.

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. load() just returns a proxy by default get() will hit the database and database won’t be hit until the immediately. methods. then use one of the get() sure that the object exists. http://javaeasytoall. get() :- load() get() If you are not sure that the object Only use the load() method if you are exists. database. proxy is first invoked. 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. and merge() if you want to Lara Technologies 080-41310124 150 . 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.

mark this collection as the “inverse” end of a bidirectional association. Coming to hibernate associations. Inverse=”true|false” Essentially “inverse” indicates which end of a relationship should be ignored. these are unidirectional. http://javaeasytoall. Cascade = “all | none | save-update | delete | all-delete-orphan” Inverse . 56) Define cascade and inverse option in one-many mapping? Cascade – enable operation to cascade to child entities.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. 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 . so when persisting a parent who has collection of children. These are bi-directional associations.

table per class hierarchy and table per concrete class These all are inheritance mapping based Lara Technologies 080-41310124 152 . but calculated at runtime by evaluation of an expression are called derived properties. http://javaeasytoall. 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. 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. 58) What are derived properties? The properties that are not mapped to a column. 62) What is table per subclass.com screens where there is a variable number of conditions to be placed upon the result set. The expression can be defined using formula attribute of the element.  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.

If you use getPublisher without closing the session then publisher is accessible. Association Mapping: Lara Technologies 080-41310124 153 . 65) Explain about collection mapping.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. then this type of mapping done is called unidirectional mapping. http://javaeasytoall. inheritance mapping? Collection Mapping: It’s a kind of mapping done in Hibernate to map a collection defined in persistent java object. the this type of mapping done is called bidirectional mapping. 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. but if we access publisher after session is closed then its an error. Hibernate basically requires persistent collection-valued fields be declared as an interface type. Set. This feature of Hibernate is called lazy initialization. If we want to get reference of child table or object while retrieving parent table or child and also vice-versa. component mapping. association mapping. This avoids unnecessary database queries and enhances the performance. Basically we can use Bag. List. Array. and Map in collection mapping as defined in Java Objects.

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. many-many. 66) What is component mapping in Hibernate?  A component is an object saved as a value. The different mapping often used is one-one. one- many. 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 .com It’s a mapping done in Hibernate generally to show the relation between persistent object. many-one. http://javaeasytoall.

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. Table per subclass 3. The sorting collection by specifying the order-by occurs in the memory of JVM which clause for sorting this collection running Hibernate. 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. 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. it will be more efficient way to sort it. http://javaeasytoall. be more efficient way to sort it . being read from database using java comparator. 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.com sorted collection vs. 71) What is table per concrete class? Lara Technologies 080-41310124 155 . If your collection is not large. We use these inheritance mapping strategies 1. it will If your collection is very large. after the data when retrieval. Table per class hierarchy 2.

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

try { tx.. It does not flush and close() automatically.. // Extra work you need to do tx. } catch (RuntimeException e) { tx..createQuery(.rollback(). // Do some work sf. session..begin().getCurrentSession(). // or display error message } openSession() : If you decide to use manage the Session yourself the go for sf. // Do some work session. you have to flush() and close() it.begin(). tx.). tx.. session.. Example : UserTransaction tx = (UserTransaction)new InitialContext() . http://javaeasytoall.persist(.com Example : try { UserTransaction tx = (UserTransaction)new InitialContext() . sf.createQuery(.lookup("java:comp/UserTransaction").flush().lookup("java:comp/UserTransaction").. throw e..persist(.).commit(). Session session = factory.).getCurrentSession(). } catch (RuntimeException e) { Lara Technologies 080-41310124 159 .openSession() .commit().openSession().).

. http://javaeasytoall. // or display error message } finally { session. session.com tx. While running the transactions. means wont process one transaction many times. 1)firstlevel(Session) caching 2)Secondlevel(SessionFactory) caching 1)firstlevel(Session) caching: First-level cache always Associates with the Session object. 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. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. throw e..save() .rollback(). // 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. Lara Technologies 080-41310124 160 . so that those objects will available to the entire application. in between it loads the objects at the Session Factory level. whenever an object is returned by the query. In this way the second level cache works.save() : Save does an insert and will fail if the primary key is already persistent. Hibernate uses this cache by default. don’t bounds to single user. at that time no need to go for a database transaction. Here.saveOrUpdate() and session.close(). it processes one transaction after another one. 80) Difference between session. Since the objects are already loaded in the cache.persist()? session. That is instead of updating after every modification done in the transaction.

persist() return void. Lara Technologies 080-41310124 161 .save(). session.println(session.persist(question)). http://javaeasytoall.persist() doesn't. Compile time error because session.println(session. if you do :- System.out.out. session.com session. But session.persist() return void. Insert data if primary key not exist otherwise update data.save() returns the generated identifier (Serializable object) and session.save(question)). This will print the generated primary key. For Example : if you do :- System.persist() : Does the same like session.save() return Serializable object but session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update.

txt index. charset=ISO-8859- 1"> <title>Insert title here</title> </head> <script> function makeRequest(url) { var httpRequest.overrideMimeType) { httpRequest.txt by clicking the link and refreshing the some portion of page by printing the content of the test. httpRequest = new XMLHttpRequest()..html we are getting test.XMLHttpRequest) {//MOZILA.overrideMimeType('text/xml').org/TR/html4/loose.w3.html <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4. } } else if(window.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html. if(window.01 Transitional//EN" "http://www.SAFARI. if(httpRequest.com AZAX Refresh a Page with text field: From index. http://javaeasytoall.ActiveXObject) {//IE try { Lara Technologies 080-41310124 162 .

XMLHTTP").setRequestHeader("Content-Type". httpRequest.true).onreadystatechange = function() {alertContents(httpRequest). } catch(e){} } } if(!httpRequest) { alert("Giving UP:con not create an XMLHTTP instance").innerHTML = httpRequest. return false. } function alertContents(httpRequest) { if(httpRequest. } httpRequest.com httpRequest = new ActiveXObject("Msxml12."application/x- www-form-urlencoded").send("").open('POST'. } catch(e) { try { httpRequest = new ActiveXObject("Microsoft. http://javaeasytoall. httpRequest. } } } Lara Technologies 080-41310124 163 . httpRequest.url.}.getElementById("lara").responseText.XMLHTTP").readyState == 4) { if(httpRequest. } else { alert("There was a problem").status == 200) { document.

org/TR/html4/loose. http://javaeasytoall.SAFARI. httpRequest = new XMLHttpRequest(). if(httpRequest..w3.txt Hello welcome to lara Refreshing a page with XML From index.html <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.html we are getting test.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html.xml index. if(window.XMLHttpRequest) {//MOZILA.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.overrideMimeType) { httpRequest.overrideMimeType('text/xml').01 Transitional//EN" "http://www. } } Lara Technologies 080-41310124 164 .charset=ISO-8859- 1"> <title>Insert title here</title> </head> <script> function makeRequest(url) { var httpRequest.com </script> <body> <a href="#" onclick="makeRequest('test.xml by clicking the button and refreshing the some portion of page by printing the content of the test.

} function alertContents(httpRequest) { if(httpRequest.onreadystatechange = function() {alertContents(httpRequest). httpRequest.getElementsByTagName('root').item(0).}. Lara Technologies 080-41310124 165 . } catch(e){} } } if(!httpRequest) { alert("Giving UP:con not create an XMLHTTP instance").com else if(window.data. } catch(e) { try { httpRequest = new ActiveXObject("Microsoft.open('POST'. document. httpRequest.send("").getElementById("lara"). httpRequest.true)."application/x- www-form-urlencoded").status == 200) { var xmldoc = httpRequest.setRequestHeader("Content-Type". return false.ActiveXObject) {//IE try { httpRequest = new ActiveXObject("Msxml12.firstChild. } httpRequest.readyState == 4) { if(httpRequest. http://javaeasytoall.XMLHTTP").url.innerHTML = root_node. var root_node = xmldoc.responseXML.XMLHTTP").

w3.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html.com } else { alert("There was a problem"). Lara Technologies 080-41310124 166 .html <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.html we are getting test.xml')"> <br><br> <div id="lara">LARA TECHNOLOGIES</div> <br><br><br> WELCOME TO AZAX </body> </html> test. } } } </script> <body> <input type="button" value="CALL XML FILE" onclick="makeRequest('test.01 Transitional//EN" "http://www.xml <?xml version="1. http://javaeasytoall.0" encoding="UTF-8"?> <root> hello welcome to lara MANIKANTA </root> Refreshing a page with JSP From index.jsp by clicking the link and refreshing the some portion of page by printing the content of the test.jsp index. charset=ISO-8859- 1"> <title>Insert title here</title> </head> <script> function makeRequest(url) { var httpRequest.org/TR/html4/loose.

SAFARI.overrideMimeType('text/xml'). httpRequest = new XMLHttpRequest(). if(httpRequest.XMLHttpRequest) {//MOZILA. } catch(e) { try { httpRequest = new ActiveXObject("Microsoft. http://javaeasytoall.}.open('POST'.XMLHTTP"). httpRequest. } catch(e){} } } if(!httpRequest) { alert("Giving UP:con not create an XMLHTTP instance"). return false.onreadystatechange = function() {alertContents(httpRequest). } httpRequest.readyState == 4) Lara Technologies 080-41310124 167 .overrideMimeType) { httpRequest.setRequestHeader("Content-Type".. httpRequest.url. httpRequest. } } else if(window.ActiveXObject) {//IE try { httpRequest = new ActiveXObject("Msxml12. } function alertContents(httpRequest) { if(httpRequest.send("").XMLHTTP").com if(window."application/x- www-form-urlencoded").true).

w3. charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4. } else { alert("There was a problem").com { if(httpRequest. charset=ISO-8859- 1"> <title>Insert title here</title> </head> <body> <% out.status == 200) { document.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html.innerHTML = httpRequest. %> </body> </html> Lara Technologies 080-41310124 168 .jsp <%@ page language="java" contentType="text/html. http://javaeasytoall. } } } </script> <body> <input type="button" value="CALL JSP FILE" onclick="makeRequest('test.getElementById("lara").org/TR/html4/loose.println("HELLO WELCOME TO LARA").jsp')"> <br><br> <div id="lara">LARA TECHNOLOGIES</div> <br><br><br> WELCOME TO AZAX </body> </html> test.01 Transitional//EN" "http://www.responseText.

if (httpRequest.txt index.xml and test. test.XMLHTTP"). // See note below about this line } } else if (window..jsp by clicking the link and refreshing the some portion of page by printing the content of the test.w3.html <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4. } catch (e) { try { httpRequest = new ActiveXObject("Microsoft. } catch (e) {} } Lara Technologies 080-41310124 169 . if (window.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html.html we are getting test.. Safari.XMLHTTP").XML.XMLHttpRequest) { // Mozilla.JSP From index.overrideMimeType) { httpRequest. http://javaeasytoall. charset=ISO-8859- 1"> <title>Insert title here</title> </head> <script type="text/javascript" language="javascript"> function makeRequest(url) { var httpRequest. httpRequest = new XMLHttpRequest().com Refreshing a page with txt.org/TR/html4/loose.01 Transitional//EN" "http://www.ActiveXObject) { // IE try { httpRequest = new ActiveXObject("Msxml2.txt. .overrideMimeType('text/xml').

httpRequest. } } } </script> <body> Lara Technologies 080-41310124 170 .indexOf('. } document.status == 200) { var str ="". httpRequest. url).getElementsByTagName('root'). } httpRequest.substring(url.innerHTML = str.setRequestHeader("Content-Type". if(url.') + 1) == "xml") { var xmldoc = httpRequest.responseXML.'). "application/x- www-form-urlencoded"). } function alertContents(httpRequest. } else { str = httpRequest. httpRequest.open('POST'.item(0).onreadystatechange = function() { alertContents(httpRequest. } else { alert('There was a problem with the request. url) { if (httpRequest.responseText.getElementById("lara"). url.readyState == 4) { if (httpRequest. return false. http://javaeasytoall.firstChild. }. true).com } if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'). str = root_node.send(""). var root_node = xmldoc.data.

jsp <%@ page language="java" contentType="text/html. charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.println("HELLO WELCOME TO LARA from jsp").jsp')"> <br> <a href="#" onclick="makeRequest('test.01 Transitional//EN" "http://www. %> </body> </html> Refreshing a page with JSP by passing one parameter Lara Technologies 080-41310124 171 .w3.com <input type="button" value="CALL XML FILE" onclick="makeRequest('test. http://javaeasytoall.org/TR/html4/loose.xml')"><br> <input type="button" value="CALL JSP FILE" onclick="makeRequest('test. charset=ISO-8859- 1"> <title>Insert title here</title> </head> <body> <% out.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.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html.

Safari.readyState == 4) { if (httpRequest. } httpRequest. } catch (e) {} } } if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'). // See note below about this line } } else if (window.com index. "application/x- www-form-urlencoded").open('POST'. param) { var httpRequest. } function alertContents(httpRequest) { if (httpRequest. if (window.overrideMimeType('text/xml').status == 200) { Lara Technologies 080-41310124 172 .send("param=" + param). httpRequest.XMLHTTP"). httpRequest. return false. http://javaeasytoall.onreadystatechange = function() { alertContents(httpRequest).. url. true).ActiveXObject) { // IE try { httpRequest = new ActiveXObject("Msxml2.overrideMimeType) { httpRequest.XMLHTTP"). } catch (e) { try { httpRequest = new ActiveXObject("Microsoft. }. . if (httpRequest..XMLHttpRequest) { // Mozilla. httpRequest.html <script type="text/javascript" language="javascript"> function makeRequest(url.setRequestHeader("Content-Type". httpRequest = new XMLHttpRequest().

} } } </script> <a href="#" onclick="makeRequest('test.'). Safari. httpRequest = new XMLHttpRequest(). %> One Simple Development index.println(request.jsp <% out.jsp'. if (window. ..overrideMimeType('text/xml')..01 Transitional//EN" "http://www.com document.innerHTML = httpRequest.getParameter("param" + ".XMLHttpRequest) { // Mozilla. field) { var httpRequest.org/TR/html4/loose.html <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.jsp</a> <br><br><br> <div id="lara"></div> test. out.responseText.overrideMimeType) { httpRequest.println("lara"). charset=ISO-8859- 1"> <title>Insert title here</title> </head> <script type="text/javascript" language="javascript"> function makeRequest(url. // See note below about this line } } Lara Technologies 080-41310124 173 . if (httpRequest.getElementById("lara").w3. } else { alert('There was a problem with the request. http://javaeasytoall.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html."). 'hello')">Make request to test.

} function populateDistricts(httpRequest) { if (httpRequest. } catch (e) {} } } if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'). true).onreadystatechange = function() { populateDistricts(httpRequest).innerHTML = httpRequest. httpRequest. } httpRequest.readyState == 4) { if (httpRequest.').com else if (window.send("stateId=" + field. return false. http://javaeasytoall. } catch (e) { try { httpRequest = new ActiveXObject("Microsoft.getElementById("districts"). url. } else { alert('There was a problem with the request.status == 200) { document. httpRequest.value).XMLHTTP").ActiveXObject) { // IE try { httpRequest = new ActiveXObject("Msxml2. }.responseText.XMLHTTP"). "application/x- www-form-urlencoded"). } } } Lara Technologies 080-41310124 174 .setRequestHeader("Content-Type".open('POST'. httpRequest.

%> </body> </html> Lara Technologies 080-41310124 175 .println("<option value='balr'>BaLary</option>"). out.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html.println("<option value='blr'>Bangaloore</option>"). out.org/TR/html4/loose.w3.println("<select name='districts'>"). http://javaeasytoall.com </script> State:<select name="state" onchange="makeRequest('test. 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. charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4. charset=ISO-8859- 1"> <title>Insert title here</title> </head> <body> <% String id = request.equals(id)) { out.println("<option value='kdp'>Kadapa</option>").getParameter("stateId"). } out.println("</select>").jsp <%@ page language="java" contentType="text/html.equals(id)) { out.println("<option value='hyd'>Hyderabad</option>"). out. out.println("<option value='tpt'>Tirupati</option>").jsp'. if("1".01 Transitional//EN" "http://www. } else if("2".

http://javaeasytoall. %> </body> </html> test.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html. charset=ISO-8859- 1"> <title>Insert title here</title> </head> <body> <% out.txt Hello welcome to lara Lara Technologies 080-41310124 176 . charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.org/TR/html4/loose.println("HELLO WELCOME TO LARA from jsp").xml <%@ page language="java" contentType="text/html.com test.01 Transitional//EN" "http://www.w3.