Hibernate
Hibernate
Hibernate
com
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
By
B.Ramesh
Here Java file sending a action to hibernate but not sql queries.
Based on the action (i.e insert or update or select) hibernate will
generate sql query and sends to the database.
If you have a requirement of using some data very frequently, instead of
reading from database every time, read once and keep in the cache and
then 2nd time onwards read from the cache, it reduces number of
network calls.
If you are using Hibernate, you can change the database one to another
at the time of development itself.
For example at the time of development you used mysql after
production your client/customer wants to change database to Oracle
then no need to do changes in your java code. You need to do changes
in the configuration file and can execute very successfully.
Hibernate id typically used in Java Swiong applications, Java Servlet
applications, or J2ee applications using session beans.
Hibernate supports “Transactions” (Transaction means making
multiple units as a single bundle i.e a transaction can contains insert,
update, delete, if any one query fails to execute then remaining also
will not execute).
We can achieve mapping through Hibernate very easely.
By Hibernate we can achieve where conditions very simple.
By Hibernate managing joins is very easy.
Hibernate is developed in java so, it is platform independent.by this we
can achieve pure object oriented (database interactions also).
Hibernate can be used for any kind of java application that can be
standalone, web-application, or enterprise application in where the
database interaction is required.
Hibernate uses Object oriented querying language.
Hibernate is free to use no need to buy any licences. It is also a
opensource, we can download the source code and can enhance.
Usage of Hibernate is nothing but using sessipn object effectively.
Hibernate maintains two level cache.
Persistant Objects
Sessoion SessionFactory
Configuration Query
Transaction
JDBC
To use Hibernate, it is required to create a java class that represents the table
in the database and then map the instance variable in the class with the
columns in the database. Then Hibernate can be used to perform operations
on the database like select, insert, update and delete the records in the table.
1. connection Management:
2. transaction Management:
3. object Relational Management:
Updating buildpath:
Hibernate API
Session (org.hibernate.Session):
Session object is similar to the HttpSession object.s A single-threaded,
short-lived object representing a conversation between the application and
the persistent store. Wraps a JDBC connection. Factory for Transaction.
Holds a mandatory (first-level)cache of persistent objects, used when
navigating the object graph or looking up objects by identifier.
SessionFactory (org.hibernate.SessionFactory):
Configuration (org.hibernate.cfg.Configuration):
Query(org.hibernate.cfg.query):
In order to construct HQL queries we use this interface. Not only this
interface we can also use Criteria interface.
Transaction (org.hibernate.Transaction):
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.
For Every framework there will be one configuration file Eg: for struts
struts-config.xml. Like wise for hibernate also there is one config file i.e
hibernate.config.xml
First develop one hibernate.config.xml for your application under
classpath. Inside this xml file we have to explian about.
1. DriverClassName.
2. URL.
3. Username to connect to database;
4. Password to connect to database.
5. Type of 2nd level cache.
6. Dialect class. Through this we are updating database
type (Dialect means pronouncing same language in
different accents).
<hibernate-configuration>
<session-factory>
<mapping resource="com/lara/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.lara;
public class Person
{
private Integer id;
private String personName;
private Integer personAge;
5. Now develop one hbm file for every Pojo class in one package.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
</class>
</hibernate-mapping>
package com.lara;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
// 1. Configuration
Configuration config = new Configuration ();
config.configure ();
7. Now start the database (i.e MySql4) and run the program.
<hibernate-configuration>
<session-factory>
<mapping resource="com/lara/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.lara;
public class Person
{
private int id;
private String personName;
private int personAge;
this.personName = personName;
}
public int getPersonAge () {
return personAge;
}
public void setPersonAge (int personAge) {
this.personAge = personAge;
}
}
5. Now develop one hbm file for every Pojo class in one package.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
package com.lara;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
// 1. Configuration
Configuration config = new Configuration ();
config.configure ();
Person p1 = (Person)session.load(com.lara.Person.class,
new Integer(id));
7. Now start the database (i.e MySql4) and run the program.
<hibernate-configuration>
<session-factory>
<property name="current_session_context_class">thread</property>
<mapping resource="com/lara/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.lara;
public class Person
{
private int id;
private String personName;
private int personAge;
}
public void setPersonName (String personName) {
this.personName = personName;
}
public int getPersonAge () {
return personAge;
}
public void setPersonAge (int personAge) {
this.personAge = personAge;
}
}
5. Now develop one hbm file for every Pojo class in one package.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
package com.lara;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
// 1. Configuration
Configuration config = new Configuration ();
config.configure ();
7. Now start the database (i.e MySql4) and run the program.
In this application we are using Mysql4 database and we want to create table
for PRODUCTS with columns
PRODUCT_NAME,PRODUCT_PRICE,PRODUCT_QUANTITY and
PRODUCT_ID.
and we want to insert,delete and edit the already stored record.
<hibernate-configuration>
<session-factory>
<property name="connection.pool_size">1</property>
<mapping resource="com/lara/Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3. Now create one package structure in “src” folder and develop one
Pojo class.
package com.lara;
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public int getProductQuantity() {
return productQuantity;
}
public void setProductQuantity(int productQuantity) {
this.productQuantity = productQuantity;
}
}
<hibernate-mapping>
</class>
</hibernate-mapping>
index.jsp
<body>
<a href="add.jsp">INSERT</a><br>
<a href="edit.jsp">EDIT</a><br>
<a href="delete.jsp">DELETE</a><br>
</body>
add.jsp
<body>
<form action="InsertServlet" method="post"><br>
Name:<input type="text" name="productName"><br>
Price:<input type="text" name="productPrice"><br>
Quantity:<input type="text" name="productQuantity"><br>
<input type="submit" value="submit">
</form>
</body>
edit.jsp
<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>
delete.jsp
<body>
<form action="DeleteServlet" method="post">
Id:<input type="text" name="id"><br>
<input type="submit" value="DELETE">
</form>
</body>
InsertServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
pdr.setProductName(pName);
pdr.setProductPrice(Double.parseDouble(pPrice));
pdr.setProductQuantity(Integer.parseInt(pQty));
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(pdr);
session.getTransaction().commit();
session.flush();
session.close();
UpdateServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
{
static final long serialVersionUID = 1L;
public UpdateServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
String id = request.getParameter("id");
String pName = request.getParameter("productName");
String pPrice = request.getParameter("productPrice");
String pQty = request.getParameter("productQuantity");
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Product p1 = (Product)session.load(Product.class,
Integer.parseInt(id));
p1.setProductName(pName);
p1.setProductPrice(Double.parseDouble(pPrice));
p1.setProductQuantity(Integer.parseInt(pQty));
session.saveOrUpdate(p1);
session.getTransaction().commit();
session.flush();
session.close();
DeleteServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Product p1 = (Product)session.load(Product.class,
Integer.parseInt(id));
session.delete(p1);
session.getTransaction().commit();
session.flush();
session.close();
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.username">system</property>
<property name="connection.password">great123</property>
<mapping resource="com/lara/Address.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Address.java
package com.lara;
}
public long getPinCodeNo() {
return pinCodeNo;
}
public void setPinCodeNo(long pinCodeNo) {
this.pinCodeNo = pinCodeNo;
}
}
Address.hbm.xml
<hibernate-mapping>
<property name="houseNo"/>
<property name="streetNo"/>
<property name="city"/>
<property name="state"/>
<property name="country"/>
<property name="pinCodeNo"/>
</class>
</hibernate-mapping>
In hbm file we are not giving any column names for property tag then it
take defaut name as property name.
index.jsp
<body>
<a href="add.jsp">Insert</a><br>
<a href="ListServlet">LIST</a><br>
<a href="search.jsp">SEARCH</a>
</body>
add.jsp
<body>
<form action="InsertServlet" method="post">
HouseNo:<input type="text" name="houseNo"><br>
StreetNo:<input type="text" name="streetNo"><br>
City:<input type="text" name="city"><br>
State:<input type="text" name="state"><br>
Country:<input type="text" name="country"><br>
PinCodeNo:<input type="text"
name="pinCodeNo"><br>
<input type="submit" value="ADD ADDRESS">
</form>
</body>
search.jsp is for searching the particular record in the table by
selsecting the column names and giving the text to search.
search.jsp
<body>
<form action="ListServlet"/>
SearchCriteria:
<select name="searchCriteria">
<option value="id">AdressId</option>
<option value="houseNo">HouseNo</option>
<option value="streetNo">StreetNo</option>
<option value="city">City</option>
<option value="state">State</option>
<option value="country">Country</option>
<option value="pinCodeNo">
PinCodeNo</option>
</select><br>
SearchText:
<input type="text" name="searchText">
<input type="submit" value="Search">
</form>
</body>
InsertServlet.java is for inserting the values into the table. If we want to
insert the servlet then we to call save() by passing the object.
InsertServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class InsertServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public InsertServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String houseNo=request.getParameter("houseNo");
String streetNo=request.getParameter("streetNo");
String city=request.getParameter("city");
String state=request.getParameter("state");
String country=request.getParameter("country");
String pinCodeNo=request.getParameter("pinCodeNo");
adr.setCity(city);
adr.setCountry(country);
adr.setHouseNo(houseNo);
adr.setPinCodeNo(Long.parseLong(pinCodeNo));
adr.setState(state);
adr.setStreetNo(streetNo);
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(adr);
session.getTransaction().commit();
session.flush();
session.close();
PrintWriter out = response.getWriter();
out.println("ADDRESS SAVED");
out.close();
}
}
UpdateServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class UpdateServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
public UpdateServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String id = request.getParameter("recordId");
String houseNo=request.getParameter("houseNo");
String streetNo=request.getParameter("streetNo");
String city=request.getParameter("city");
String state=request.getParameter("state");
String country=request.getParameter("country");
String pinCodeNo=request.getParameter("pinCodeNo");
adr.setId(new Integer(id));
adr.setCity(city);
adr.setCountry(country);
adr.setHouseNo(houseNo);
adr.setPinCodeNo(Long.parseLong(pinCodeNo));
adr.setState(state);
adr.setStreetNo(streetNo);
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.saveOrUpdate(adr);
session.getTransaction().commit();
session.flush();
session.close();
ListServlet.java is for listing all the records from table. If we want to list
all the records then we want to use Criteria interface or Query
interface. In this application we are using Criteria.If we want to create
object for Criteria interface then there is a method createCriteria ()
which there inside the session class.
Eg: session.createCriteria(Address.class);
ListServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Expression;
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Expression.sql(sc+"='"+st+"'");
for(int i=0;i<list.size();i++)
{
add = (Address)list.get(i);
out.println("<tr>");
out.println("<td>");
out.println("<a href='DetailedServlet?recordId="
+add.getId()+"'>");
out.println(add.getId());
out.println("</a>");
out.println("</td>");
out.println("<td>");
out.println(add.getHouseNo());
out.println("</td>");
out.println("<td>");
out.println(add.getStreetNo());
out.println("</td>");
out.println("<td>");
out.println(add.getCity());
out.println("</td>");
out.println("<td>");
out.println(add.getState());
out.println("</td>");
out.println("<td>");
out.println(add.getCountry());
out.println("</td>");
out.println("<td>");
out.println(add.getPinCodeNo());
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("<a href='index.jsp'>Home</a>");
session.getTransaction().commit();
session.flush();
session.close();
}
}
DetailedServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
SessionFactory sf = config.buildSessionFactory();
session.beginTransaction();
session.getTransaction().commit();
session.flush();
session.close();
}
}
DeleteServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.delete(add);
session.getTransaction().commit();
session.flush();
session.close();
DisplayForEdit.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
SessionFactory sf = config.buildSessionFactory();
session.beginTransaction();
session.getTransaction().commit();
session.flush();
session.close();
}
}
What are all the algorithms for attribute “class” of “generator ” tag of “id”
tag ?
The types of algorithms are:
1. hilo
2. seqhilo
3. uuid
4. guid
5. sequence
6. identity
7. select
hibernate.cg.xml
<hibernate-configuration>
<session-factory>
org.hibernate.cache.NoCacheProvider </property>
<mapping resource="com/lara/Book.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Book.java
package com.lara;
}
public void setBookAuther(String bookAuther) {
this.bookAuther = bookAuther;
}
Book.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<property name="bookName"/>
<property name="bookAuther"/>
<property name="bookPrice"/>
</class>
</hibernate-mapping>
addBook.jsp
<body>
<form action=” AddBookServlet” method=”post”>
</body>
AddBookServlet.java
package com.lara;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
book.setBookName("JAVA");
book.setBookAuther("MAHESH");
book.setBookPrice(450.50);
SessionFactory sf = config.buildSessionFactory();
session.beginTransaction();
session.save(book);
session.getTransaction().commit();
session.flush();
session.close();
PrintWriter out=response.getWriter();
Out.println(“check in the database.”);
}
}
All algorithms will not support all the databases only few algorithms
only support particular databases.
Create one folder where ever and copy that cfg file into that folder then
come to the program and at the time of configuration give the path of the
folder.
EG:
Src|
|----cfg|
|----hibernate.cfg.xml
Now come to the program
Configuration config = new Configuration();
config.configure("config/hibernate.cfg.xml");
Cascade types:
all,create,merge,save-update,delete,lock,refresh,evict,replicate.
1. Relational Mapping
(a) One-to-One Mapping
(b) One-to-Many and Many-to-one Mapping
(c) Many-to-many Mapping
2. Polymorphic Mapping.
(a) One table per Class hierarchy
(b) One table per Sub-Class
(c) One table per Concreate-Class
3. Component Mapping.
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<mapping resource="com/lara/Person.hbm.xml"/>
<mapping resource="com/lara/ Mail.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Person.java
package com.lara;
this.mailId = mailId;
}
}
Mail.java
package com.lara;
User.hbm.xml
<hibernate-mapping>
</class>
</hibernate-mapping>
Mail.hbm.xml
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
</class>
</hibernate-mapping>
Manager.java
package com.lara;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
mail.setPersonId("p101");
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(p1);
session.getTransaction().commit();
session.flush();
session.close();
}
}
Example2:
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<mapping resource="com/lara/User.hbm.xml"/>
<mapping resource="com/lara/ UserDetails.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.java
package com.lara;
UserDetails.java
package com.lara;
}
public void setEduc(String educ) {
this.educ = educ;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
User.hbm.xml
<hibernate-mapping>
</class>
</hibernate-mapping>
UserDetails.hbm.xml
<hibernate-mapping>
</class>
</hibernate-mapping>
Manager.java
package com.lara;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
{
public static void main(String[] args)
{
User user = new User();
user.setUserId("index101");
user.setUserAge(23);
user.setUserEmail("manikanta@gmail.com");
user.setUserFirstName("MANIKANTA");
user.setUserLastName("CHOUDHARY");
user.setUserMobileNo("9986340298");
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.flush();
session.close();
}
Usually foreign key is used for to join the two tables In this example we
want to join User and UserDetails. In this we are using one-to-one join if one
modification is done in one table then that modifications will reflect back
to another table also.
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">great123</property>
<mapping resource="com/lara/Batch.hbm.xml"/>
<mapping resource="com/lara/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Student.java
package com.lara;
Batch.java
package com.lara;
import java.util.HashSet;
import java.util.Set;
Batch.hbm.xml
<hibernate-mapping package="com.lara">
</class>
</hibernate-mapping>
Manager.java
package com.lara;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
//CONFIGURATION OF HIBERNATE
SessionFactory sf = config.buildSessionFactory();
session.beginTransaction();
//1.INSERTION
/*
session.save(batch);
session.getTransaction().commit();
*/
// Randomly UPDATE
/*
Batch batch = (Batch)session.load(Batch.class,3);
Iterator it = batch.getStudents().iterator();
Student std = null;
if(it.hasNext())
{
std = (Student) it.next();
}
std.setFirstName("CHAGED MANIKANTA");
session.saveOrUpdate(std);
session.getTransaction().commit();
*/
}
std.setFirstName("CHANGED AGAIN MANIKANTA");
session.saveOrUpdate(std);
*/
/*
Batch batch = (Batch) session.load(Batch.class, 3);
Student std = null;
Iterator it = batch.getStudents().iterator();
while(it.hasNext())
{
std = (Student)it.next();
if(std.getId() == 2)
{
break;
}
}
batch.getStudents().remove(std);
session.delete(std);
*/
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<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;
Batch.java
package com.lara;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Batch
{
private Integer id;
private String batchName;
private Date startDate;
private Integer duration;
private Integer fee;
private Set participents = new HashSet();
std.getBatch().add(this);
}
public void removeParticipentsFromBatch(Student std)
{
participents.remove(std);
std.getBatch().remove(this);
}
}
Student.hbm.xml
<hibernate-mapping package="com.lara">
</hibernate-mapping>
Batch.hbm.xml
<hibernate-mapping package="com.lara">
</class>
</hibernate-mapping>
Manager.java
package com.lara;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
{
//add();
//readBatchWiseStudents(3);
//UpdateParticularStudent(3,102,"Changed MANIKANTA");
deletingRecord(4,104);
}
private static void add()
{
Batch b1 = new Batch();
b1.setId(3);
b1.setBatchName("REGULAR JAVA");
b1.setDuration(120);
b1.setFee(5000);
SessionFactory sf = getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(b1);
session.save(b2);
session.save(std);
session.save(std1);
session.save(std2);
session.save(std3);
session.getTransaction().commit();
session.flush();
session.close();
}
session.beginTransaction();
Batch b = (Batch)session.load(Batch.class, i);
Set students = b.getParticipents();
Iterator allStudents = students.iterator();
Student std = null;
while(allStudents.hasNext())
{
std = (Student)allStudents.next();
System.out.println(std.getId()+":"+std.getStdName());
}
session.getTransaction().commit();
session.flush();
session.close();
}
package com.lara;
Now develop one hbm file for every Pojo class in one package.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
</class>
</hibernate-mapping>
package com.lara;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
config.setProperty("cache.provider_class ",
“org.hibernate.cache.NoCacheProvider”);
config.setProperty("show_sql ", “true”);
config.setProperty("hbm2ddl.auto ", “update”);
config.addResource(“com/lara/Person.hbm.xml”);
System.out.println(“Hibernate got configured.”);
session.beginTransaction ();
System.out.println(“transaction started..”);
session.saveOrUpdate(p1);
System.out.println(“person object saved/updated.”);
session.flush ();
System.out.println(“session got flushed..”);
session.close ();
System.out.println(“session got closed..”);
}
}
Now start the database (i.e Oracle) and run the program.
package com.lara;
}
public void setOrderPrice(int orderPrice) {
this. orderPrice = orderPrice;
}
Now develop one hbm file for every Pojo class in one package.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
</class>
</hibernate-mapping>
package com.lara;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
config.addResource(“com/lara/Person.hbm.xml”);
System.out.println(“Hibernate got configured.”);
session.beginTransaction ();
System.out.println(“transaction started..”);
session.save(order);
System.out.println(“person object saved.”);
session.flush ();
System.out.println(“session got flushed..”);
session.close ();
System.out.println(“session got closed..”);
}
System.out.println(order.getOrderId());
System.out.println(order.getOrderName());
System.out.println(order.getOrderDate());
System.out.println(order.getOrderDescription());
System.out.println(order.getOrderPrice());
System.out.println(order.getOrderBy());
}
*/
//same can be achieved through query
/*
Criteria ctr = session.createCriteria(com.lara.Order.class);
Ctr.add(Restrictions.sqlRestriction(“orderDescription”,like “%h%”
abc));
Query query=session.createQuery(“from com.lara.Order”);
List<Order> list = query.list();
For(Order order : list)
{
System.out.println(order.getOrderId());
System.out.println(order.getOrderName());
System.out.println(order.getOrderDate());
System.out.println(order.getOrderDescription());
System.out.println(order.getOrderPrice());
System.out.println(order.getOrderBy());
}
*/
}
Now start the database (i.e Oracle) and run the program.
Polymorphic mappings:
hibernate.cfg.xml
<mapping resource="com/lara/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Person.java
package com.lara;
Employee.java
package com.lara;
PermanentEmployee.java
package com.lara;
Person.hbm.xml
<hibernate-mapping package="com.lara">
Manager.java
package com.lara;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
Person.hbm.xml
<hibernate-mapping package="com.lara">
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.password"></property>
<mapping resource="com/lara/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Person.java
package com.lara;
public class Person
{
private String id;
Person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
</hibernate-mapping>
Manager.java
package com.lara;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Manager{
public static void main(String[] args)
{
/*
Person p1 = new Person();
p1.setId("INDEX104");
p1.setFirstName("MANI");
p1.setLastName("KANTA");
p1.setPersonAge(23);
*/
Configuration config = new Configuration();
config.configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
System.out.println(p.getId()+":"+p.getFirstName()
+":"+p.getPersonAge());
}
//session.save(p1);
session.getTransaction().commit();
session.flush();
session.close();
}
}
If we want to make two attributes as primary key field then create separate
class for two attributes and that class should implement Serialization and
override equals() and hashCode().
EG:
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<mapping resource="com/lara/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Person.java
package com.lara;
public class Person
{
private PKField pkField;;
private String lastName;
private Integer personAge;
PKField.java
package com.lara;
import java.io.Serializable;
PKField pk = (PKField)obj;
return id.equals(pk.id)&& firstName.equals(pk.firstName);
}
public int hashCode()
{
return id.hashCode()+firstName.hashCode();
}
Person.hbm.xml
<hibernate-mapping package="com.lara">
Manager.java
package com.lara;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Iterator<Person> it = query.iterate();
while(it.hasNext())
{
Person p = it.next();
System.out.println(p.getPkField().getFirstName());
}
//session.save(p1);
session.getTransaction().commit();
session.flush();
session.close();
/*
// To read a record
PKField pk1 = new PKField();
Pk.setId (101);
Pk.setFirstName(“abc”);
Person p2= (Person)session.load(com.lara.Person.class,pk1);
System.out.println(p2.getLastName());
System.out.println(p2.getPersonAge());
System.out.println(p2. PKField ().getId());
System.out.println(p2. PKField ().getFirstName());
*/
/*
// To get all records
List<Person> list=session.createCriteria
(com.lara.Person.class, list)
For(Person p1 : list)
{
System.out.println(p2.getLastName());
System.out.println(p2.getPersonAge());
System.out.println(p2. PKField ().getId());
System.out.println(p2. PKField ().getFirstName());
}
*/
/*
// To update one record
PKField pk1 = new PKField();
Pk.setId (101);
Pk.setFirstName(“abc”);
Session.saveOrUpdate(p2);
*/
/*
// To delete one record
Session.delete(p2);
*/
Java Annotations
The Basics
Annotation Types
Example:
Usage:
@MyAnnotation
public void mymethod() {
....
}
Single-Element: Single-element, or single-value type,
annotations provide a single piece of data only. This
can be represented with a data=value pair or, simply
with the value (a shortcut syntax) only, within
parenthesis.
Example:
Usage:
Example:
Usage:
Annotations
Simple Annotations
Override
Deprecated
Suppresswarnings
Example 1
public class Test_Override {
@Override
public String toString() {
return super.toString() +
" Testing annotation name: 'Override'";
}
}
TestJavaApplication1buildclasses
D:tempNew Folder (2)TestJavaApplication1srctest
myannotationTest_Override.java:24: method does
not override
a method from its superclass
@Override
1 error
BUILD FAILED (total time: 0 seconds)
Example 2
public TestAnnotations() {
Test_Deprecated t2=new Test_Deprecated();
t2.doSomething();
}
Example 3
public class TestAnnotations {
public static void main(String arg[]) throws
Exception {
new TestAnnotations().doSomeTestNow();
}
@SuppressWarnings({"deprecation"})
public void doSomeTestNow() {
Test_Deprecated t2 = new Test_Deprecated();
t2.doSomething();
}
}
Target
Retention
Documented
Inherited
@Target(ElementType.METHOD)—can be applied to a
method level annotation
@Target(ElementType.PARAMETER)—can be applied to
the parameters of a method
@Target(ElementType.CONSTRUCTOR)—can be applied
to constructors
@Target(ElementType.LOCAL_VARIABLE)—can be
applied to local variables
@Target(ElementType.ANNOTATION_TYPE)—indicates
that the declared type itself is an annotation type
Example 4
@Target(ElementType.METHOD)
public @interface Test_Target {
public String doTestTarget();
}
The only change you can see from above is that the
annotation declaration is shifted from method-level to field-
level, which is not correct. Because you have defined your
annotation @Test_Target to be applicable only at method-
level, if you try to compile this class, you are likely to get
something like this:
"TestAnnotations.java":
D:R_AND_DTestAnnotationsrctestmyannotation
TestAnnotations.java:16:
annotation type not applicable to this kind of
declaration at line
16, column 0
@Test_Target(doTestTarget="Hello World !")
^
Error in javac compilation
Example 5
@Retention(RetentionPolicy.RUNTIME)
public @interface Test_Retention {
String doTestRetention();
}
Example 6
@Documented
public @interface Test_Documented {
String doTestDocument();
}
Figure 1
Example 7
@Inherited
public @interface myParentObject {
boolean isInherited() default true;
String doSomething() default "Do what?";
}
@myParentObject
public Class myChildObject {
}
Do you see the difference? You can see that you will have to
implement all the methods that the parent interface owns.
Besides the isInherited() and doSomething() methods from
myParentObject, you will have to implement the equals(),
toString(), and hasCode() methods of java.lang.Object and
also the annotationType() method of
java.lang.annotation.Annotation class. It does not matter
whether you want to implement these methods or not; you
will have to include these in your inherited object.
1. annotation: the mega data that u will use in ur code to give it some
life. It is specific usage of that type.
2. annotation-type: is used for defining an annotation. It is actual
construct used.
The Annotation appears first, often on its own line, and may include
elements with named or unnamed values.
Instead of writing hbm file we can keep that information, we can write
through anotations.it will act as a member as like class,interface, enum
etc.anotations mainly to give.
.Examle:
@Documented: when ever you are using this annotation that .java file java
documentation method is available.(it also should be documented.)
To use annotation for providing mapping information without hbm file in the
hibernate. To avoid mapping resource inside hibernate-mapping tag.
For that update the buildpath with 4 types of JAR files they are:
examlpe1:
class A
{
@diprecated
String test()
{
System,out,println(“Dipricated method.”);
}
}
Class Manager
{
Public static void main(String args[])
{
A a1=new A();
A1.test();
Examle2:
Class Test
{
@suppresswarnings(“unchecked”)
Public static void main(String args[])
{
ArrayList list=new ArrayList();
List.add(10);
}
}
class A
{
@HelloAnnotation(hello=”welcome to all.”)
}
class B extends A
{
{
@TestAnnotation(count=100, date=02-02-2009)
}
Example: hibernate programe with usage of annotations.
import javax.persistance.column;
import javax.persistance.entity;
import javax.persistance.Id;
import javax.persistance.jable;
@Entity
@Table(name=”Person”)
@column(name=”person_name”)
privateString personName;
package com.lara;
Session.beginTransaction();
Session.save(p1);
Session.getTransaction.commit();
Session.flush();
Session.close();
}
}
CacheManagement:
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
Persistent objects :
FAQS
Faqs
1) What is ORM?
The entire application, including the user interface, is designed around the
relational model and SQL-based relational operations.
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
i. Pure relational:
Improved productivity
Answer 2 : There are many benefits from these. Out of which the
following are the most important one.
6) What is Hibernate?
1. Use JavaBeans
JDBC Hibernate
With JDBC, developer has to write Hibernate is flexible and powerful
code to map an object model's data ORM solution to map Java classes to
POJO stands for Plain Old Java Objects. These are just basic JavaBeans
that have defined setter and getter methods for all the properties that are
there in that bean. Besides they can also have some business logic related
ORM tools require a metadata format for the application to specify the
mapping between classes and tables, properties and columns, associations
and foreign keys, Java types and SQL types. This information is called
the object/relational mapping metadata. It defines the transformation
between the different data type systems and relationship representations.
Hibernate simplifies:
14) What is the file extension you use for hibernate mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to
load and store objects. Typical mapping file look as follows:
• Mapping files (*.hbm.xml): These files are used to map persistent objects
to a relational database. It is the best practice to store each object in an
individual mapping file (i.e mapping file per class) because storing large
number of persistent classes into one mapping file can be difficult to manage
and maintain. The naming convention is to use the same name as the
persistent (POJO) class name. For example Account.class will have a
mapping file named Account.hbm.xml. Alternatively hibernate annotations
can be used as part of your persistent class code instead of the *.hbm.xml
files.
Programmatic configuration
Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>
Or
Derived properties
There are many benefits from these. Out of which the following are the
most important one.
Session is a lightweight and non thread safe object that represents a single-
unit-of-work with the database. Sessions are opened by SessionFactory and
closed when all the work is complete. It represents a persistence manager
that manages operations like storing and retrieving objects from database.
Instances of sessions are inexpensive to create and destroy.
This is a property file that should be placed in application class path. So when the
Configuration object is created, hibernate is first initialized. At this moment the
application will automatically detect and read this hibernate.properties file.
hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class =
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class =
net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect
41). What are detached objects, transient object, and persistent object?
Transient Objects:
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.
Cons: Working with detached objects is quite cumbersome and using Data
Transfer Object for the presentation layers
is better than using detached
objects.
Persistent Object:
Hibernate uses the version property if there exist one or uses identifier
value.
HQL stands for Hibernate Query Language. Hibernate allows the user to
express queries in its own portable SQL extension and this is called as
HQL. It also allows the user to express in native SQL.
Answer 2 :
Named SQL queries are defined in the mapping xml document and called
wherever required.
Example:
load() get()
If you are not sure that the object
Only use the load() method if you are
exists, then use one of the get()
sure that the object exists.
methods.
load() method will throw an exception get() method will return null if the
if the unique id is not found in the unique id is not found in the
database. database.
load() just returns a proxy by default
get() will hit the database
and database won’t be hit until the
immediately.
proxy is first invoked.
Map
Inverse=”true|false”
The properties that are not mapped to a column, but calculated at runtime by
evaluation of an expression are called derived properties. The expression can
be defined using formula attribute of the element.
62) What is table per subclass, table per class hierarchy and table per
concrete class
Book—–publisher
Many to one
Collection Mapping:
Association Mapping:
Component-mapping:
Example:
68) What is inheritance mapping strategy? (OR) What are the different
approaches to represent an inheritance hierarchy?
It’s a typical strategy to map “whole object graph” which are related to each
other through inheritance. We use these inheritance mapping strategies
1. Table per class hierarchy 2. Table per subclass 3. Table per concrete
class
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.
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 ?
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:
Example :
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
// Do some work
sf.getCurrentSession().createQuery(...);
sf.getCurrentSession().persist(...);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
openSession() :
If you decide to use manage the Session yourself the go for
sf.openSession() , you have to flush() and close() it.
It does not flush and close() automatically.
Example :
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
try {
tx.begin();
// Do some work
session.createQuery(...);
session.persist(...);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close(); // Extra work you need to do
}
79) Give me simple example of hibernate caching and explain the details
of caching?
2)Secondlevel(SessionFactory) caching
Second-level cache always associates with the Session
Factory object. While running the transactions, in between
it loads the objects at the Session Factory level, so that
those objects will available to the entire application,
don’t bounds to single user. Since the objects are already
loaded in the cache, whenever an object is returned by the
query, at that time no need to go for a database
transaction. In this way the second level cache works.
session.save() : Save does an insert and will fail if the primary key is
already persistent.
AZAX
httpRequest = new
ActiveXObject("Msxml12.XMLHTTP");
}
catch(e)
{
try
{
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(!httpRequest)
{
alert("Giving UP:con not create an XMLHTTP instance");
return false;
}
httpRequest.onreadystatechange = function()
{alertContents(httpRequest);};
httpRequest.open('POST',url,true);
httpRequest.setRequestHeader("Content-Type","application/x-
www-form-urlencoded");
httpRequest.send("");
}
function alertContents(httpRequest)
{
if(httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
document.getElementById("lara").innerHTML =
httpRequest.responseText;
}
else
{
alert("There was a problem");
}
}
}
</script>
<body>
<a href="#" onclick="makeRequest('test.txt')">
Make a request for Text File
</a><br><br>
<div id="lara">LARA TECHNOLOGIES</div>
<br><br><br>
WELCOME TO AZAX
</body>
</html>
test.txt
Hello welcome to lara
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script>
function makeRequest(url)
{
var httpRequest;
if(window.XMLHttpRequest)
{//MOZILA,SAFARI..
httpRequest = new XMLHttpRequest();
if(httpRequest.overrideMimeType)
{
httpRequest.overrideMimeType('text/xml');
}
}
else if(window.ActiveXObject)
{//IE
try
{
httpRequest = new
ActiveXObject("Msxml12.XMLHTTP");
}
catch(e)
{
try
{
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(!httpRequest)
{
alert("Giving UP:con not create an XMLHTTP instance");
return false;
}
httpRequest.onreadystatechange = function()
{alertContents(httpRequest);};
httpRequest.open('POST',url,true);
httpRequest.setRequestHeader("Content-Type","application/x-
www-form-urlencoded");
httpRequest.send("");
}
function alertContents(httpRequest)
{
if(httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
var xmldoc = httpRequest.responseXML;
var root_node =
xmldoc.getElementsByTagName('root').item(0);
document.getElementById("lara").innerHTML =
root_node.firstChild.data;
}
else
{
alert("There was a problem");
}
}
}
</script>
<body>
<input type="button" value="CALL XML FILE"
onclick="makeRequest('test.xml')">
<br><br>
<div id="lara">LARA TECHNOLOGIES</div>
<br><br><br>
WELCOME TO AZAX
</body>
</html>
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
hello welcome to lara MANIKANTA
</root>
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script>
function makeRequest(url)
{
var httpRequest;
if(window.XMLHttpRequest)
{//MOZILA,SAFARI..
httpRequest = new XMLHttpRequest();
if(httpRequest.overrideMimeType)
{
httpRequest.overrideMimeType('text/xml');
}
}
else if(window.ActiveXObject)
{//IE
try
{
httpRequest = new
ActiveXObject("Msxml12.XMLHTTP");
}
catch(e)
{
try
{
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(!httpRequest)
{
alert("Giving UP:con not create an XMLHTTP instance");
return false;
}
httpRequest.onreadystatechange = function()
{alertContents(httpRequest);};
httpRequest.open('POST',url,true);
httpRequest.setRequestHeader("Content-Type","application/x-
www-form-urlencoded");
httpRequest.send("");
}
function alertContents(httpRequest)
{
if(httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
document.getElementById("lara").innerHTML =
httpRequest.responseText;
}
else
{
alert("There was a problem");
}
}
}
</script>
<body>
<input type="button" value="CALL JSP FILE"
onclick="makeRequest('test.jsp')">
<br><br>
<div id="lara">LARA TECHNOLOGIES</div>
<br><br><br>
WELCOME TO AZAX
</body>
</html>
test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<body>
<%
out.println("HELLO WELCOME TO LARA");
%>
</body>
</html>
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script type="text/javascript" language="javascript">
function makeRequest(url) {
var httpRequest;
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function()
{ alertContents(httpRequest, url); };
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-
www-form-urlencoded");
httpRequest.send("");
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
var str ="";
if(url.substring(url.indexOf('.') + 1) == "xml")
{
var xmldoc = httpRequest.responseXML;
var root_node =
xmldoc.getElementsByTagName('root').item(0);
str = root_node.firstChild.data;
}
else
{
str = httpRequest.responseText;
}
document.getElementById("lara").innerHTML = str;
} else {
alert('There was a problem with the request.');
}
}
}
</script>
<body>
</body>
</html>
index.html
<script type="text/javascript" language="javascript">
function makeRequest(url, param) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function()
{ alertContents(httpRequest); };
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-
www-form-urlencoded");
httpRequest.send("param=" + param);
}
function alertContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
document.getElementById("lara").innerHTML =
httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
</script>
<a href="#" onclick="makeRequest('test.jsp', 'hello')">Make request to
test.jsp</a>
<br><br><br>
<div id="lara"></div>
test.jsp
<%
out.println(request.getParameter("param" + ",");
out.println("lara");
%>
One Simple Development
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<script type="text/javascript" language="javascript">
function makeRequest(url, field) {
var httpRequest;
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function()
{ populateDistricts(httpRequest); };
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-
www-form-urlencoded");
httpRequest.send("stateId=" + field.value);
function populateDistricts(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
document.getElementById("districts").innerHTML =
httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}
</script>
test.xml
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<body>
<%
out.println("HELLO WELCOME TO LARA from jsp");
%>
</body>
</html>
test.txt
Hello welcome to lara