http://www.mkyong.com/tutorials/spring-tutorials/http://static.springsource.org/spring/docs/2.5.x/reference/index.htmlhttp...
package r4r;public class Emp {int id;String name,job;int salary;public Emp() {    super();}public Emp(String name, String ...
<!DOCTYPE hibernate-mapping PUBLIC    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://hibernate.sourceforge.net/hi...
//PersistTest.javapackage r4r;import java.util.*;import org.hibernate.Session;import org.hibernate.Transaction;public clas...
•     Session:-This is a main interface throw which application eveloper interact. This interface          provide method ...
public String getName() {return name;}public void setName(String name) {this.name = name;}public int getId() {return id;}p...
}3- Create Emp.hbm.xml file:-<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate M...
5- Create a main class// SelectTest.javapackage r4r;import java.util.Scanner;import org.hibernate.Session;import org.hiber...
is used to start a transaction.             public Transaction begintransaction();      •    createQuery:-          is use...
2-Sequence Generator:-             sequence gnerator uses the sequence define in the database for generating id.Example:-C...
1- Table Per Class Hierarchy:- In this approach objects of all the classes of a family aremapped to asingle table in a dat...
3-Table Per Class:-In this approach one table for each class of the family is created. Each table containsfields to repres...
one to one is changed to one to many then this approach went to wrong.1- Using Primary Key-Foreign Key Relation:-Consider ...
}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getCity() {return city;}public void...
//PkFk.hbm.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0/...
session.save(a);session.save(p);t.commit();session.close();System.out.println("successfully inserted");}catch(Exception e)...
<generator class="foreign"><param name="property">address</param></generator></id><property name="name"></property><one-to...
</id><property name="city"></property><property name="street"></property></class><class name="r4r.Person" table="person3">...
// Batch.javapackage r4r;public class Batch {int id;String time,course,mode;Trainer trainer;public Batch() {super();}publi...
public class Trainer {int id;String name;Set<Batch> batches;public Trainer() {super();}public Trainer(String name) {super(...
package mypack;import java.util.*;import org.hibernate.Session;import org.hibernate.Transaction;public class PersistTest {...
Example Of Many To Many Mapping:-//hibernate.cfg.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-configuration PU...
package r4r;import java.util.*;public class Emp {int id;String name,job;int salary;Set<Privilage> privilages;public Emp() ...
package r4r;import java.util.Set;public class Privilage {int id;String name;int cost;Set<Emp> employees;public Privilage()...
<class name="r4r.Privilage"><id name="id" type="int"><generator class="increment"></generator></id><property name="name"/>...
Iterator<privilage> itr=pr.iterator();                      while(itr.hasNext())                      {                   ...
Advantages Of Using HQL:-1- HQL queries are database independent.2-HQL provide a support for ordering the result persist o...
from classname as Aliasex-1- To fetch all the emp object:-Query q=Session.createQuery("From Emp e")-2- To fetch only Those...
<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//E...
}public int getSalary() {return salary;}public void setSalary(int salary) {this.salary = salary;}}//Emp.hbm.xml<?xml versi...
System.out.println(emp.getName()+"t"+emp.getSalary());}session.close();}}Example of Select Program in HQL:-  hibernate.cfg...
package mypack;public class Student {        int id;        String name;        String subject;         public Student() {...
</class></hibernate-mapping>package mypack;import java.util.Iterator;import java.util.List;import   org.hibernate.Query;im...
Hibernate support caching at two levels:-1- First Level Caching2-Second Level CachingFirst Level Caching :-(Transactional ...
Hibernate Specification says that cache provider must defined block in memory forstoring object. I these storing block obj...
<session-factory>        <property name="connection.username">system</property>        <property name="connection.url">jdb...
</hibernate-mapping>ehcache.xml:-<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC          "-//Hiberna...
public Emp() {                super();        }        public Emp(String name, String job, int salary, Set<Previlige> priv...
int id;String name;int cost;Set<Emp> users;public Previlige() {        super();}public Previlige(String name, int cost) { ...
}}S2Test.java:-package r4r;import   java.util.*;import   org.hibernate.*;import   org.hibernate.cfg.Configuration;import  ...
}}Working With Collection In Hibernate:-Collection is widely used in hibernate .Example:--hibernate.cfg.xml<?xml version=1...
</id><property name="name"/><bag name="song" table="songs1" cascade="all"><key column="personid"/><many-to-many class="r4r...
package r4r;public class Songs {         int id;         String info;         public Songs() {                 super();   ...
public class InsertTest {         public static void main(String[] args) {                  try                  {        ...
<mapping resource="Login.hbm.xml"/></session-factory></hibernate-configuration>Creating Login.hbm.xml file<?xml version=1....
}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword...
public boolean find(String name,String password){Configuration cfg=new Configuration().configure();SessionFactory f=cfg.bu...
return "failure";}public Login getL() {return l;}public void setL(Login l) {this.l = l;}public String getName() {return na...
personal.java(pojo class)package mypack;public class personal {int id;String name;String Student;String specializationin;p...
<id name="id" type="int"><generator class="increment"/></id><property name="name"/><property name="student"/><property nam...
response.setContentType("text/html");PrintWriter out=response.getWriter();Configuration cfg=new Configuration().configure(...
Registration Form Using Struts HibernateFirst add capabilities of Struts and hibernate Then:-.hibernate.cfg.xml<?xml versi...
package mypack;public class Registration {        int id;        String name,password,email;       public Registration() {...
Registration.hbm.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC          "-//Hibernate/Hibernate ...
</s:form>a.jsp<b>successfully inserted</b>Struts.xml<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apa...
51.1.Introduction:-The Struts 2.x is the web application framework in Java Technology, thisframework provide the concept o...
<filter-name>struts2</filter-name>                 <filter-class>                 org.apache.struts2.dispatcher.ng.filter....
package org.r4r;public class HelloWorld {           private String message;           public String getMessage() {        ...
1. Introduction of Spring Framework 2.51.1 .Introduction :-The Spring Framework is a lightweight open source application f...
Modules of Spring Framework1.3 .Scope of Spring Framework :- There are many scope of spring framework which areCore , AOP ...
ORM (Object Relation Mapping):-This modules build over the JDBC that provide the facilityof integration spring application...
used to object. Object can be shared among and loose coupling between object and user can beprovided. Following two approa...
3.5 .BeanFactory:-BeanFactory is an interface provided by spring framework . This interfacerepresent the functionality of ...
System.out.println(hello);          }}                                            HelloTest.javapackage org.r4r;import   o...
<bean id="hello" class="org.r4r.Hello"><constructor-arg value="Hello World !"/></bean>5.4 .Object Creation Using factory m...
}     }Following configuration need to provided the IOC container to use getB() factory method.<bean id="b" class="A" fact...
<?xml version="1.0" encoding="UTF-8"?><beans        xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="...
OutPut:-This message is generated by method.This message is generated by Constructor.           7.Object Create Example Us...
int x=in.nextInt();                   System.out.println("Enter the second number:-");                   int y=in.nextInt(...
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
75255741 very-important-example-of-hibernate3-0
Upcoming SlideShare
Loading in...5
×

75255741 very-important-example-of-hibernate3-0

375
-1

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
375
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

75255741 very-important-example-of-hibernate3-0

  1. 1. http://www.mkyong.com/tutorials/spring-tutorials/http://static.springsource.org/spring/docs/2.5.x/reference/index.htmlhttp://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/http://www.mkyong.com/struts2/struts-2-spring-integration-example/http://r4r.co.in/java/struts/basic/tutorial/struts2.0/index.shtmlhttp://www.java2s.com/Code/Java/Hibernate/CascadeSaveOrUpdate.htmhttp://www.techienjoy.com/struts2-upload-example.phphttp://www.techienjoy.com/Spring.phphttp://www.interview-questions-tips-forum.net/http://r4r.co.in/java/http://r4r.co.in/java/spring/basic/tutorial/spring2.5/First Application Of HibernateIt is a first application which persist data into database:Step 1:-first we create a hibernate.cfg.xml file:Hibernate uses the hibernate.cfg.xml to create the connection pooland setup required environment.// 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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="connection.url">jdbc:mysql://localhost:3306/test</property><property name="connection.username">root</property><property name="connection.password">root</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><mapping resource="Emp.hbm.xml"/></session-factory></hibernate-configuration>Step 2:-write first java persistance class.// Emp.java
  2. 2. package r4r;public class Emp {int id;String name,job;int salary;public Emp() { super();}public Emp(String name, String job, int salary) { super(); this.name = name; this.job = job; this.salary = salary;}public int getId() { return id;}public void setId(int id) { this.id = id;}public String getName() { return name;}public void setName(String name) { this.name = name;}public String getJob() { return job;}public void setJob(String job) { this.job = job;}public int getSalary() { return salary;}public void setSalary(int salary) { this.salary = salary;}}Step:3 -// Mapping the Emp Object to the Database Emp tableThe file Emp.hbm.xml is used to map Emp Object to the Emp table in the database. Here is the codefor Emp.hbm.xml:<?xml version=1.0 encoding=UTF-8?>
  3. 3. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="r4r.Emp" ><id name="id" type="int"><generator class="increment" /></id><property name="name" /><property name="job" /><property name="salary" type="int"/></class></hibernate-mapping>Step 4:-//SessionProvider is created for creating the object of session.//sessionProvider.javapackage r4r;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class SessionProvider {static SessionFactory factory;static{Configuration cfg=new Configuration().configure();factory=cfg.buildSessionFactory();}public static Session getSession() { return factory.openSession();}}Step5:-// main java class
  4. 4. //PersistTest.javapackage r4r;import java.util.*;import org.hibernate.Session;import org.hibernate.Transaction;public class PersistTest { public static void main(String[] args) { Scanner in=new Scanner(System.in); Session session=SessionProvider.getSession(); Transaction t=session.beginTransaction(); while(true) { System.out.println("Enter Name:"); String n=in.nextLine(); System.out.println("Enter Job:"); String j=in.nextLine(); System.out.println("Enter Salary:"); int s=in.nextInt(); in.nextLine();// to remove unread newline character. Emp e=new Emp(n,j,s); session.save(e); System.out.println("want to persist more objects yes/no?"); String ans=in.nextLine(); if(ans.equals("no")) break; } t.commit(); session.close(); System.out.println("successfully persisted."); }}Commonly used classes and interfaces exposed by hibernate for applicationdeveloper:- • Configurtion:- Configuration object is used by the hibernate to stored configuration information in object form.Configuration information data is required by hibernate to connect to a database and information of classes that are to be managed by hibernate. • SessionFactory:- It is a factory class which is used by application developer to create session.A part from this it can also be used to manage second level cache .
  5. 5. • Session:-This is a main interface throw which application eveloper interact. This interface provide method for persistance object,creating tansaction and query objects for each user a different session is provided. • Transaction:-This interface is used by appliction developer to transact execution query. • Query:- This interface is used by he application developer to execute HQL query. HQL is a object version of sql used by hibernate.A simple select program of Hibernate :-1- Create hibernate.hbm.xml file<?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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property><property name="connection.username">system</property><property name="connection.password">system</property><property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><mapping resource="Emp.hbm.xml"/></session-factory></hibernate-configuration>2- Create Emp.java class:-package r4r;public class Emp {int id;String name,job;int salary;
  6. 6. public String getName() {return name;}public void setName(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getJob() {return job;}public void setJob(String job) {this.job = job;}public int getSalary() {return salary;}public void setSalary(int salary) {this.salary = salary;}
  7. 7. }3- Create Emp.hbm.xml file:-<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- r4r.co.in. --><hibernate-mapping><class name="mypack.Emp"><id name="id" type="int"></id><property name="name"></property><property name="job"></property><property name="salary" type="int"></property></class></hibernate-mapping>4- Create Session provider class// SessionProvider.javapackage r4r;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class SessionProvider {static SessionFactory factory;static{Configuration cfg=new Configuration().configure();factory=cfg.buildSessionFactory();}public static Session getSession(){return factory.openSession();}}
  8. 8. 5- Create a main class// SelectTest.javapackage r4r;import java.util.Scanner;import org.hibernate.Session;import org.hibernate.Transaction;public class SelectTest {public static void main(String rr[]){Session session=SessionProvider.getSession();Transaction t=session.beginTransaction();// List<Emp> list=new List<Emp>;Scanner in=new Scanner(System.in);System.out.println("enter id:-");int id=in.nextInt();Emp e=(Emp)session.load(Emp.class,id);System.out.println("followin records are fetched:-");System.out.println(e.getId()+"t"+e.getName()+"t"+e.getJob()+"t"+e.getSalary());t.commit();session.close();}}Some Important Methods Of Hibernate:- • save():- method of Session interface is used to persist object. public void save (Object o); • delete():- is used to remove a persistent object. public void delete(Object o); • refresh():- is used to Synchronized the state of a persistaent logc to the database. public void refresh(Object o); • beginTransaction:-
  9. 9. is used to start a transaction. public Transaction begintransaction(); • createQuery:- is used to obtain query object.Query object is used to run sql query. public query createquery();etc • ID Generator:-Id generator is used to autogenerate id of objects.Different batabase support different types ofgenerator.most commonly used generaor that are supported by oracle are: 1-increment 2-sequential 1. increment:- Increment generator uses highest value of primary key increases to generator id value. Example:- Consider previous example of Student,in which id generator is used as:<?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"><!-- r4r.co.in. --><hibernate-mapping><class name="r4r.Student"><id name="id" type="int"><generator class="increment"></generator></id><property name="name"></property><property name="course"></property></class></hibernate-mapping>
  10. 10. 2-Sequence Generator:- sequence gnerator uses the sequence define in the database for generating id.Example:-Consider Emp example<?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"><!-- r4r.co.in. --><hibernate-mapping><class name="r4r.Emp"><id name="id" type="int"><generator class="sequence"><param name="sequence">oursequence</param></generator></id><property name="name"></property><property name="job"></property><property name="salary" type="int"></property></class></hibernate-mapping>Hibernate Mapping:- There are two types of mapping: 1-Is -A Mapping 2-Has-A Mapping 1. Is-A Mapping:- Is a relation between persistent object can be implemented in the following three ways- 1- Table per class Hierarchy 2- Table per subclass 3- Table per class
  11. 11. 1- Table Per Class Hierarchy:- In this approach objects of all the classes of a family aremapped to asingle table in a database. This table contain field to represent combined data member of all theclasses ofthe family plus an additional fields is used to describe record of the table ,that is, to identified whichrecordof table represent object of which class of the familyAdvantages Of This Approach:-Major advantages of this approach is performance. Because hibernate need to manage toallthe classes to the family.Disadvantages Of This Approach:-1-Table is not normalized2-Not Null constraint can not be applied non the field representing data member of subclass2-Table Per Subclasses:-In this approach one table for each class of the faimily is created. Table for the parent class containsfieldto represenent parent class data member and table for the subclasses contains fields to represent theirown data member.Primary key of parent table is used for hierarchy in table for subclasses.Advantages- • Tables are noralized • Not null constraint can be appliedDisadvantages:- • performance is degraded becouse to insert and fetched subclsses object .Multiple queries or joins are required • Tables are not fully normalized.
  12. 12. 3-Table Per Class:-In this approach one table for each class of the family is created. Each table containsfields to represents declared as well as inherited data member of the class.Advantages:- • Tables are fully normalized. • Not null constraint cn be applied on all the table of fields. • Better performance.Disadvantages:- • Relation of object is losses in the table. • This approach s not supported in the all ORM framework. Has-A- Mapping:-Has-A relation between object can be of following types:-1-One-to-One (Unidirectional and bidirectional)2-One-to-Many (Unidirectional and bidirectional)3-Many-to-Many (Unidirectional and bidirectional)1-One-to-One Mapping:-One to one mapping between object can be implement with the three ways-In case of unidirectional:-1- Using primary key-foreign key relation2- Using same primary Key3-Using relation tableDisadvantages:-This approach can only be used if relation between objects which be one to one .If in future
  13. 13. one to one is changed to one to many then this approach went to wrong.1- Using Primary Key-Foreign Key Relation:-Consider two classes first Address(owned object) and second Person(owner object) .In address therearethree fields ,id,street and city. And in person table it contains id,name,address.Example:-//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"><!-- r4r.co.in. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property><property name="connection.username">system</property><property name="connection.password">system</property><propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><mapping resource="PkFk.hbm.xml"/></session-factory></hibernate-configuration>//Address.javapackage r4r;public class Address {int id;String city,street;public Address() {}public Address(String city, String street) {super();this.city = city;this.street = street;
  14. 14. }public int getId() {return id;}public void setId(int id) {this.id = id;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getStreet() {return street;}public void setStreet(String street) {this.street = street;}}//Person.javapackage r4r;public class Person {int id;String name;Address address;public Person() {super();}public Person(String name, Address address) {super();this.name = name;this.address = address;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}}
  15. 15. //PkFk.hbm.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="r4r.Address"><id name="id" type="int"><generator class="increment"></generator></id><property name="city"></property><property name="street"></property></class><class name="r4r.Person"><id name="id" type="int"><generator class="increment"></generator></id><property name="name"></property><many-to-one name="address" class="r4r.Address" column="addressid" unique="true"cascade="all"></many-to-one></class></hibernate-mapping>//InsertTest.javapackage r4r;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class InsertTest {public static void main(String[] args) {try{Configuration cfg=new Configuration().configure();SessionFactory f=cfg.buildSessionFactory();Session session=f.openSession();Transaction t=session.beginTransaction();Address a=new Address("noida","u.p");Person p=new Person("name",a);
  16. 16. session.save(a);session.save(p);t.commit();session.close();System.out.println("successfully inserted");}catch(Exception e){System.out.println("exception thrown");}}}2-Same Primary Key Mapping:-In this approach owner and owned shared same primary key value.Advantages:-It eliminate the need of foreign key.Disadvantages:-1- A special id is generator is required to used id of one object as id of another.2- If it converted into one-to-many then this approach will not be used.Example:-//SamePk.hbm.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="r4r.Address"><id name="id" type="int"><generator class="increment"></generator></id><property name="city"></property><property name="street"></property></class><class name="r4r.Person"><id name="id" type="int">
  17. 17. <generator class="foreign"><param name="property">address</param></generator></id><property name="name"></property><one-to-one name="address" class="r4r.Address" cascade="all"></one-to-one></class></hibernate-mapping>3-Using Relation Table:-In this approach the relation table is used to manage the relation between obect.Primary key of both objects are used as foreign key in relation table .Advantages:-support one-to-many ,if any time one name has many address then it support it .Disadvantage:-Performance is degraded.Example:-In this approach three tables are used1- Table for Batch(id,name)2-Table for Trainer(id,name,fees)3-Table for Relation(batchid,trainerid)<?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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="r4r.Address"><id name="id" type="int"><generator class="increment"></generator>
  18. 18. </id><property name="city"></property><property name="street"></property></class><class name="r4r.Person" table="person3"><id name="id" type="int"><generator class="increment"></generator></id><property name="name"></property><join table="addresses"><key column="personid"><many-to-one name="address" class="r4r.Address" cascade="all" column="addressid"unique="true"></many-to-one></join></class></hibernate-mapping> 2-One-to-Many Mapping:-This type of association relates one entity object to many object of another entity.Example:-Relationship between a department and employee.Many employee can work in a single department.//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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property><property name="connection.username">system</property><property name="connection.password">system</property><propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><mapping resource="listAndBag.hbm.xml"/></session-factory></hibernate-configuration>
  19. 19. // Batch.javapackage r4r;public class Batch {int id;String time,course,mode;Trainer trainer;public Batch() {super();}public Batch(String time, String course, String mode,Trainer t) {super();this.time = time;this.course = course;this.mode = mode;this.trainer=t;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getTime() {return time;}public void setTime(String time) {this.time = time;}public String getCourse() {return course;}public void setCourse(String course) {this.course = course;}public String getMode() {return mode;}public void setMode(String mode) {this.mode = mode;}public Trainer getTrainer() {return trainer;}public void setTrainer(Trainer trainer) {this.trainer = trainer;}} //Trainer.javapackage r4r;import java.util.*;
  20. 20. public class Trainer {int id;String name;Set<Batch> batches;public Trainer() {super();}public Trainer(String name) {super();this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Batch> getBatches() {return batches;}public void setBatches(Set<Batch> batches) {this.batches = batches;}}//sessionProvider.javapackage r4r;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class SessionProvider {static SessionFactory factory;static{Configuration cfg=new Configuration().configure();factory=cfg.buildSessionFactory();}public static Session getSession() {return factory.openSession();}}//PersisTest.java
  21. 21. package mypack;import java.util.*;import org.hibernate.Session;import org.hibernate.Transaction;public class PersistTest {public static void main(String[] args) {Trainer tr=new Trainer("Rama");Batch b1=new Batch("9 to 11","Core", "w/d",tr);Batch b2=new Batch("12 to 3", "J2ee", "w/e",tr);Batch b3=new Batch("9 to 12", "Hibernate", "w/e",tr);Session s=SessionProvider.getSession();Transaction t=s.beginTransaction();s.save(b1);s.save(b2);s.save(b3);t.commit();s.close();System.out.println("persisted.");}} Many-To-Many Mapping:-In order to implement many-to-many bidirectional relation between object.Each participants relationobject of the relation contains the properties.One of these object is designed as the owner of the relation and the other is as owned by usinginwards attributes of collection mapping.This type of relation relates many objects of an entity to many object of anothe entity.Example:- consider an example of employee and privileges A employee can get manyprivileges and many employee can get a single privileges.So here is an many-to-many mapping
  22. 22. Example Of Many To Many Mapping:-//hibernate.cfg.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><!-- R4r.co.in. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property><property name="connection.username">system</property><property name="connection.password">system</property><propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><mapping resource="m-to-m.hbm.xml"/></session-factory></hibernate-configuration>//Emp.java
  23. 23. package r4r;import java.util.*;public class Emp {int id;String name,job;int salary;Set<Privilage> privilages;public Emp() {super();// TODO Auto-generated constructor stub}public Emp(String name, String job, int salary, Set<Privilage> privilages) {super();this.name = name;this.job = job;this.salary = salary;this.privilages = privilages;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getJob() {return job;}public void setJob(String job) {this.job = job;}public int getSalary() {return salary;}public void setSalary(int salary) {this.salary = salary;}public Set<Privilage> getPrivilages() {return privilages;}public void setPrivilages(Set<Privilage> privilages) {this.privilages = privilages;}}//Privilage.java
  24. 24. package r4r;import java.util.Set;public class Privilage {int id;String name;int cost;Set<Emp> employees;public Privilage() {super();// TODO Auto-generated constructor stub}public Privilage(String name, int cost, Set<Emp> employees) {super();this.name = name;this.cost = cost;this.employees = employees;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getCost() {return cost;}public void setCost(int cost) {this.cost = cost;}public Set<Emp> getEmployees() {return employees;}public void setEmployees(Set<Emp> employees) {this.employees = employees;}}//m-to-m.hbm.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping>
  25. 25. <class name="r4r.Privilage"><id name="id" type="int"><generator class="increment"></generator></id><property name="name"/><property name="cost" type="int"/><set name="employees" table="empprivilage" inverse="true"><key column="privilageid"/><many-to-many column="empid" class="r4r.Emp"/></set></class><class name="r4r.Emp"><id name="id" type="int"><generator class="increment"/></id><property name="name"/><property name="job"/><property name="salary"/><set name="privilages" inverse="true" cascade="all" table="empprivilage"><key column="empid"/><many-to-many column="privilageid" class="r4r.Privilage"/></set></class></hibernate-mapping>//Selecttest.javapackage r4r;import java.util.Iterator;import java.util.Scanner;import java.util.Set;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Selecttest { public static void main(String[] args) { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); Session session=f.openSession(); Scanner in=new Scanner(System.in); System.out.println("enter empid"); int empid=in.nextInt(); Emp emp=(Emp) session.load(Emp.class,empid); System.out.println("employees details"); System.out.println(emp.getName()+"t"+emp.getJob()+"t"+emp.getSalary()); System.out.println("following privilages are enjoyed:"); Set<privilage> pr=emp.getPrivilages();
  26. 26. Iterator<privilage> itr=pr.iterator(); while(itr.hasNext()) { Privilage pre=itr.next(); System.out.println(pre.getId()+"t"+pre.getName()+"t"+pre.getCost()); } System.out.println("enter privilage id:"); int privilageid=in.nextInt(); Privilage privilages=(Privilage)session.load(Privilage.class,privilageid); System.out.println("following privilage detais:"); System.out.println(privilages.getName()+"t"+privilages.getCost()); System.out.println("employee benifited are:-"); Set<emp> emp11=privilages.getEmployees(); System.out.println("following employees are benifited: "); Iterator<emp> eitr=emp11.iterator(); while(eitr.hasNext()) { Emp e=eitr.next(); System.out.println(e.getName()+"t"+e.getJob()+"t"+e.getSalary()); } session.close(); }} HQL (Hibernate Query Language):-It is an object based version of SQL, it is used by hibernate to fetch data.Hibernate even provide a criterion API that provide a type safe and object orientedway to retrieve object from database.Using SQL has following shortcoming: 1- SQL is standarized but it is vendor -dependent features. 2-SQL is designed more specifically to work with relational database tables but not object.To overcome these issues Hibernate introduce its own object oriented query language calledHibernate Query Language(HQL).
  27. 27. Advantages Of Using HQL:-1- HQL queries are database independent.2-HQL provide a support for ordering the result persist objects.3-HQL is more object oriented which makes us write more easily than Sql.4- HQL support pagination.Step To Execute HQL queries Using Hibernate:-The following three steps are required in executeing HQL queries.1- Obtaining an instance of org.hibernate.Query2-Customize the Query object3-Execute the QueryStep 1- Obtaining an instance of org.hibernate.Query:-A Query instance is obtained by calling Session.createQuery() or Session.getNamedQuery method.The createQuery() method is used to create a new instance of Query for given HQL Query.Step 2- Customize the Query object:-After obtaining the query object we may want to customize it by setting query parameter ,cachemode ,Flush mode,fetch size ,an upper limit for the result set.Step 3- Execute the Query:-After preparing the query object by setting all custom properties we use list(),scroll(),iterate oruniqueResult().Syntax Of HQL Queries:-To fetch the all the object of a type:-
  28. 28. from classname as Aliasex-1- To fetch all the emp object:-Query q=Session.createQuery("From Emp e")-2- To fetch only Those object to class which satisfy given condition from classname as Alias where conditionex- To fetch all those employee who earn more 75000/monthfrom Emp e where e.salary>750003-To fetch name of all managerselect e.name from Emp e where e.job="manager"Note:-HQL queries supports named as well as positioned parametersFirst Approach:-(positioned parameter):-Query q=session.createQuery("select e.name from Emp ee.job=?");q.setString(1,job);// value of positioned parameter is set.Second Approach(Named parameter):-Query q=session.createQuery("from Emp e wheree.salary>:salary");q.setInt("salary",s);Simple Program Of Select in HQL:-Step1- Create hibernate.cfg.xml
  29. 29. <?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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property><property name="connection.username">system</property><property name="connection.password">system</property><propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><mapping resource="Emp.hbm.xml"/></session-factory></hibernate-configuration>Step2- Create Persitent class//Emp.javapackage mypack;public class Emp {int id;String name,job;int salary;public Emp() {super();}public Emp(String name, String job, int salary) {super();this.name = name;this.job = job;this.salary = salary;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getJob() {return job;}public void setJob(String job) {this.job = job;
  30. 30. }public int getSalary() {return salary;}public void setSalary(int salary) {this.salary = salary;}}//Emp.hbm.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="mypack.Emp"><id name="id" type="int"></id><property name="name"></property><property name="job"></property><property name="salary" type="int"></property></class></hibernate-mapping>//PersistTest.javapackage mypack;import java.util.*;import org.hibernate.Query;import org.hibernate.Session;public class PersistTest {@SuppressWarnings("unchecked")public static void main(String[] args) {Session session=SessionProvider.getSession();Query q=session.createQuery("from Emp e");List<Emp> e=(List<Emp>) q.list();Iterator<Emp> itr=e.iterator();System.out.println("following data fetched");while(itr.hasNext()){Emp emp=itr.next();
  31. 31. System.out.println(emp.getName()+"t"+emp.getSalary());}session.close();}}Example of Select Program in HQL:- 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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <propertyname="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="Student.hbm.xml"/> </session-factory></hibernate-configuration>Student.java
  32. 32. package mypack;public class Student { int id; String name; String subject; public Student() { super(); } public Student(String name, String subject) { super(); this.name = name; this.subject = subject; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; }}<?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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping> <class name="mypack.Student" table="stud"> <id name="id" type="int"> <generator class="increment"/> </id> <property name="name"/> <property name="subject"/>
  33. 33. </class></hibernate-mapping>package mypack;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;public class InsertDemo { @SuppressWarnings("unchecked") public static void main(String[] args) { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); Session session=f.openSession(); Query q=session.createQuery("from Student"); List<Student> student=q.list(); Iterator<Student> itr=student.iterator(); while(itr.hasNext()) { Student s=itr.next(); System.out.println(s.getName()); } session.close(); } }Hibernate Caching caching is the facility of storing objecttemporallyin the memory . The purpose of caching to improve the performance by reducing database hits . Ifsame object isrequired by different session or user then it make sense to fetch them only one and to store them intothe cacheso that they can provide the cache each time they are requested.
  34. 34. Hibernate support caching at two levels:-1- First Level Caching2-Second Level CachingFirst Level Caching :-(Transactional scope caching):- First level caching is implicitly enable. It is implemented bysession . Fist level caching is responsible for storing the object used by user.Object in this cache hastransactionalscope, once the transaction is completed object of this cache are synchronize to the database andcache is discarded.Second Level Cache (Application Scope caching):- Second level cache is not enable by default. This cache has a applicationscope,Object in this cache are shared by multiple users. This cache is managed by sessionFactoryNOTE:- Hibernate does not provide implementation of Second level caching , it onlyprovide specification how second level cache should be implemented. Third partyimplementation ofsecond level cache are available:.1- EHCACHE ( Easy hibernate Caching)2-OSCACHE (Open source caching)Specification Of second Level Cache:-
  35. 35. Hibernate Specification says that cache provider must defined block in memory forstoring object. I these storing block objects are stored in it.Each block must have name and must have some additional properties.Second level cache is divided into two parts :-1- Object cache2-Query Cache 1-Object Cache:- In object ache ,object along with there relation are stored in SimplifiedForm. 2-Query Cache:- In query cache, Queries are stored along with the ID of fetched object.For the implementation of query cache two reasons are created in memory1- In first reason query along with the value of parameter to stored as key and id ofreturned object are stored as value.2- In second region time stamp of query execution is stored. The Purpose of this region isto identified whether result of query is valid or notProgram Of EHCache:-Example: This example shows the implementation of EHCachehibernate.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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration>
  36. 36. <session-factory> <property name="connection.username">system</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.password">oracle</property> <propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <propertyname="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.generate_statistics">true</property> <property name="hibernete.ca"></property> <mapping resource="m-to-m.hbm.xml"/> </session-factory></hibernate-configuration>m-to-m.hbm.xml:-<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="mypack.Previlige"><cache usage="read-write"/><id name="id" type="int"><generator class="increment" /></id><property name="name"/><property name="cost" type="int"/><set name="users" table="empPrevilige" inverse="true"><key column="previligeId"/><many-to-many class="mypack.Emp" column="empId" /></set></class><class name="mypack.Emp"><cache usage="read-write"/><id name="id" type="int"><generator class="sequence" ><param name="sequence">keygenerator</param></generator></id><property name="name" /><property name="job" /><property name="salary" type="int"/><set name="previliges" table="empPrevilige" cascade="all"><cache usage="read-write"/><key column="empId"/><many-to-many class="mypack.Previlige" column="previligeId" /></set></class>
  37. 37. </hibernate-mapping>ehcache.xml:-<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="mypack.Previlige"><cache usage="read-write"/><id name="id" type="int"><generator class="increment" /></id><property name="name"/><property name="cost" type="int"/><set name="users" table="empPrevilige" inverse="true"><key column="previligeId"/><many-to-many class="mypack.Emp" column="empId" /></set></class><class name="mypack.Emp"><cache usage="read-write"/><id name="id" type="int"><generator class="sequence" ><param name="sequence">keygenerator</param></generator></id><property name="name" /><property name="job" /><property name="salary" type="int"/><set name="previliges" table="empPrevilige" cascade="all"><cache usage="read-write"/><key column="empId"/><many-to-many class="mypack.Previlige" column="previligeId" /></set></class></hibernate-mapping>Emp.java:-package r4r;import java.util.*;public class Emp { int id; String name,job; int salary; Set<Previlige> priviliges;
  38. 38. public Emp() { super(); } public Emp(String name, String job, int salary, Set<Previlige> priviliges){ super(); this.name = name; this.job = job; this.salary = salary; this.priviliges = priviliges; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public Set<Previlige> getPriviliges() { return priviliges; } public void setPriviliges(Set<Previlige> priviliges) { this.priviliges = priviliges; }}Previlage.java:-package r4r;import java.util.Set;public class Previlige {
  39. 39. int id;String name;int cost;Set<Emp> users;public Previlige() { super();}public Previlige(String name, int cost) { super(); this.name = name; this.cost = cost;}public int getId() { return id;}public void setId(int id) { this.id = id;}public String getName() { return name;}public void setName(String name) { this.name = name;}public int getCost() { return cost;}public void setCost(int cost) { this.cost = cost;}public Set<Emp> getUsers() { return users;}public void setUsers(Set<Emp> users) { this.users = users;}}SessionProvider.java:-package r4r;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class SessionProvider {static SessionFactory factory;static{Configuration cfg=new Configuration().configure();factory=cfg.buildSessionFactory();}public static Session getSession() { return factory.openSession();
  40. 40. }}S2Test.java:-package r4r;import java.util.*;import org.hibernate.*;import org.hibernate.cfg.Configuration;import org.hibernate.stat.SecondLevelCacheStatistics;public class S2Test { public static void main(String[] args) { try { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); for(int i=1;i<=2;i++) { Session s=f.openSession(); Date d1=new Date(); Emp e=(Emp)s.load(Emp.class, 52501); Set<Previlige> set=e.getPriviliges(); Date d2=new Date(); System.out.println("query took "+(d2.getTime()-d1.getTime())+ " milliseconds "+i+" time."); System.out.println("Emp Details:"); System.out.println(e.getName()+"t"+e.getJob()+"t"+ e.getSalary()); System.out.println("previliges details..."); Iterator<Previlige> itr=set.iterator(); while(itr.hasNext()) { Previlige pr=itr.next(); System.out.println(pr.getId()+"t"+pr.getName()+"t" +pr.getCost()); } s.close(); SecondLevelCacheStatistics sts1 = f.getStatistics(). getSecondLevelCacheStatistics("mypack.Emp"); System.out.println("details of Emp cache region:"); System.out.println(sts1); SecondLevelCacheStatistics sts2 = f.getStatistics(). getSecondLevelCacheStatistics("mypack.Previlige"); System.out.println("details of previlige cache region:"); System.out.println(sts2); } }catch(Exception e) { System.out.println(e); }
  41. 41. }}Working With Collection In Hibernate:-Collection is widely used in hibernate .Example:--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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <propertyname="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="ListCollection.hbm.xml"/> </session-factory></hibernate-configuration><?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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="r4r.Songs" table="songs"><id name="id" type="int"><generator class="increment" ></generator></id><property name="info"/></class><class name="r4r.Persons" table="persons"><id name="id" type="int"><generator class="increment"></generator>
  42. 42. </id><property name="name"/><bag name="song" table="songs1" cascade="all"><key column="personid"/><many-to-many class="r4r.Songs" column="songid"/></bag></class></hibernate-mapping>package r4r;import java.util.List;public class Persons { int id; String name; List<Songs> song; public Persons() { super(); // TODO Auto-generated constructor stub } public Persons(String name, List<Songs> song) { super(); this.name = name; this.song = song; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Songs> getSong() { return song; } public void setSong(List<Songs> song) { this.song = song; }}
  43. 43. package r4r;public class Songs { int id; String info; public Songs() { super(); } public Songs(String info) { super(); this.info = info; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; }}package r4r;import java.util.ArrayList;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;
  44. 44. public class InsertTest { public static void main(String[] args) { try { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); Session session=f.openSession(); ArrayList<Songs> list=new ArrayList<Songs>(); list.add(new Songs("mast mast laila")); list.add(new Songs("dhink ckika")); Persons p=new Persons("sushant",list); Transaction t=session.beginTransaction(); session.save(p); t.commit(); session.close(); System.out.println("successfully inserted"); } catch(Exception e) { System.out.println(e); } }}Struts Hibernate Connectivity:-There is a code of Struts and hibernate connectivity ,Steps required are as follows:This example show how to create login form using struts and hibernate.Creating hibernate.cfg.xml file<?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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property><property name="connection.username">system</property><property name="connection.password">system</property><propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  45. 45. <mapping resource="Login.hbm.xml"/></session-factory></hibernate-configuration>Creating Login.hbm.xml file<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- r4r.co.in. --><hibernate-mapping><class name="mypack.Login"><id name="id"><generator class="increment"/></id><property name="name"/><property name="password"/></class></hibernate-mapping>Creating Java Persistent Class named Login.javapackage mypack;public class Login {int id;String name,password;public Login() {super();}public Login(String name, String password) {super();this.name = name;this.password = password;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;
  46. 46. }public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}Creating Jsp pages://index.jsp<%@taglib uri="/struts-tags" prefix="s"%><s:form action="login"><s:textfield name="name" label="Name"></s:textfield><s:textfield name="password" label="Password"></s:textfield><s:submit value="submit"></s:submit></s:form>//a.jsp<b>successfully login</b>//b.jsp<b>incorrect username or password</b>-Creating DAO classpackage mypack;import java.util.Iterator;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class DAO {@SuppressWarnings("unchecked")
  47. 47. public boolean find(String name,String password){Configuration cfg=new Configuration().configure();SessionFactory f=cfg.buildSessionFactory();Session session=f.openSession();//Scanner in=new Scanner(System.in);Query q=session.createQuery("from Login e where e.name=? and e.password=?");q.setParameter(0,name);q.setParameter(1,password);Iterator<Login> itr=q.iterate();while(itr.hasNext()){session.close();return true;}session.close();return false;}}-Creating Struts.xml file<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration2.1//EN""http://struts.apache.org/dtds/struts-2.1.dtd"><struts><package name="demo" extends="struts-default"><action name="login" class="mypack.LoginAction"><result name="success">/a.jsp</result><result name="failure">/b.jsp</result></action></package></struts>Creating LoginAction.java classpackage mypack;public class LoginAction {Login l;String name;String password;public String execute(){DAO dao=new DAO();if(dao.find(getName(), getPassword()))return "success";else
  48. 48. return "failure";}public Login getL() {return l;}public void setL(Login l) {this.l = l;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}Servlet And Hibernate Connectivity:-This example shows the connectivity between servlet and hibernatehibernate.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"><!-- r4r.co.in. --><hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property><property name="connection.username">system</property><property name="connection.password">system</property><propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><mapping resource="personal.hbm.xml"/></session-factory></hibernate-configuration>
  49. 49. personal.java(pojo class)package mypack;public class personal {int id;String name;String Student;String specializationin;public personal() {super();}public personal(String name, String student, String specializationin) {super();this.name = name;Student = student;this.specializationin = specializationin;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getStudent() {return Student;}public void setStudent(String student) {Student = student;}public String getSpecializationin() {return specializationin;}public void setSpecializationin(String specializationin) {this.specializationin = specializationin;}}personal.hbm.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="mypack.personal">
  50. 50. <id name="id" type="int"><generator class="increment"/></id><property name="name"/><property name="student"/><property name="specializationin"/></class></hibernate-mapping>index.jsp<html><body><form action="Detail" method="get">Name<input type="text" name="id" value=""/><input type="submit" value="submit"/></form></body></html>Detail.java(servlet class)package mypack;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Detail extends HttpServlet {private static final long serialVersionUID = 1L;SessionFactory f;Session session;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String name=request.getParameter("id");int name1=Integer.parseInt(name);
  51. 51. response.setContentType("text/html");PrintWriter out=response.getWriter();Configuration cfg=new Configuration().configure();f=cfg.buildSessionFactory();session=f.openSession();personal p=(personal) session.get(personal.class,name1);out.println("<html");out.println("<body><table border=1>");out.println("<tr><td>name</td><td>student</td><td>specialisationin</td></tr>");out.println("following record are fetched:");out.print("<tr><td>");out.print(p.getName());out.print("</td>");out.print("<td>");out.print(p.getStudent());out.print("</td");out.print("<td>");out.print(p.getSpecializationin());out.print("</td");out.print("</tr>");out.println("</table></body>");out.println("</html>");session.close();}}web.xml<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>Detail</servlet-name><servlet-class>mypack.Detail</servlet-class></servlet><servlet-mapping><servlet-name>Detail</servlet-name><url-pattern>/Detail</url-pattern></servlet-mapping></web-app>
  52. 52. Registration Form Using Struts HibernateFirst add capabilities of Struts and hibernate Then:-.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"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <propertyname="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="Registration.hbm.xml"/> </session-factory></hibernate-configuration>Registration.java
  53. 53. package mypack;public class Registration { int id; String name,password,email; public Registration() { super(); } public Registration(String name, String password, String email) { super(); this.name = name; this.password = password; this.email = email; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}
  54. 54. Registration.hbm.xml<?xml version=1.0 encoding=UTF-8?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-mapping><class name="mypack.Registration"><id name="id" type="int"><generator class="increment"></generator></id><property name="name"/><property name="password"/><property name="email"/></class></hibernate-mapping>DAO.javapackage mypack;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class DAO { public void insert(Object o) { Configuration cfg=new Configuration().configure(); SessionFactory f=cfg.buildSessionFactory(); Session session=f.openSession(); Transaction t=session.beginTransaction(); session.save(o); t.commit(); session.close(); }}index.jsp<%@ taglib uri="/struts-tags" prefix="s"%><s:form action="Reg"><s:textfield name="r.name" label="name"></s:textfield><s:textfield name="r.password" label="password"></s:textfield><s:textfield name="r.email" label="email"></s:textfield><s:submit value="register"></s:submit>
  55. 55. </s:form>a.jsp<b>successfully inserted</b>Struts.xml<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts><package name="demo" extends="struts-default"><action name="Reg" class="mypack.RegistrationAction"><result name="success">/a.jsp</result></action></package></struts>RegistrationAction.javapackage mypack;public class RegistrationAction { Registration r; public String execute() { DAO dao=new DAO(); dao.insert(r); return "success"; } public Registration getR() { return r; } public void setR(Registration r) { this.r = r; }} Spring Frame work 2.551.How can integrate Struts 2.x and Spring Framework
  56. 56. 51.1.Introduction:-The Struts 2.x is the web application framework in Java Technology, thisframework provide the concept of Model View Controller (MVC) and Interceptor to develop theweb application. The Spring framework provide the facility to integrate with other frameworkand Developed the application in java. This tutorial provide the facility how can integratebetween Spring framework and Struts 2.x .51.2.How can integrate Spring framework and Struts 2.x:- Following steps are required to integrate Spring framework and Struts 2.xframework:-Step 1:-First select the web project in our IDE and add the capability of spring 2.5 and Struts2.x (it means that add the jar file ).Step 2:-Also add struts2-spring-plugin-2.0.jar file.Step 3:-Create configuration file struts.xml in src folder to give the struts configurationinformation.Step 4:-Also create applicationContext.xml in WEB-INF folder to give the spring configurationinformation.Step 5:-Create Action class to send the string of controller class to invoked the jsp page.Step 6:-Mapped the ContextLoaderListener class in web.xml file. 52.Example of Struts 2.x ,Spring 2.5 integration52.1.Introduction:-This tutorial provide the example to integrate between struts2 and springframework.52.2 .Technology use to run this source code:- 1.Spring2.5 jar file 2.Eclips Id 3.Tomcat Server52.3 .Source Code:- web.xml<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Struts2Example14</display-name> <filter>
  57. 57. <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app> applicationContext.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN""http://www.springframework.org/dtd/spring-beans.dtd"><beans> <bean id="helloWorldClass" class="org.r4r.HelloWorld" > </bean></beans> struts.xml<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd"><struts> <package name="default" extends="struts-default"> <action name="helloWorld" class="helloWorldClass"> <result name="success">/success.jsp</result> </action> </package></struts> HelloWorld.java
  58. 58. package org.r4r;public class HelloWorld { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String execute() { return "success"; }} index.jsp<%@taglib uri="/struts-tags" prefix="s"%><s:form action="helloWorld"><s:textfield name="message" label="Name"></s:textfield><s:submit></s:submit></s:form> success.jsp<%@taglib uri="/struts-tags" prefix="s"%>Welcome, <s:property value="message"/>OutPut:-
  59. 59. 1. Introduction of Spring Framework 2.51.1 .Introduction :-The Spring Framework is a lightweight open source application framework thatprovide facility to develop enterprise application in java platform. Spring is an application framework i.e based on two concept first one is IOC(Inversion of Control ) and second one is AOP (Aspect Oriented Programming ). This frameworkdoes not confined it self to any specific domain or API. It can be used a console application ,web application , enterprise application etc. It mean that this is a general purpose framework.1.2 .Overview :-The Spring Framework is a general purpose framework that provide followingmodules.
  60. 60. Modules of Spring Framework1.3 .Scope of Spring Framework :- There are many scope of spring framework which areCore , AOP , Context , TX , JDBC , ORM , Web MVC , Web , Struts Integration , EnterpriseIntegration and Testing . Spring all scope which are describe following :-Core:-This modules provide basic implementation of IOC container. It provide Dependencyinjection, Object creation and Lifecycle management .The important basic concept is factorymethod to control the object creation by the IOC container and application developerusing singleton or prototype model. AOP (Aspect Oriented Programming ):- This modules build over the core and providethe concept of cross-cutting concern. The cross-cutting concern first one is concern , theconcern is a task that perform as part of an operation and second one is cross-cutting, thecross-cutting is a set of concern that participate multiple operation.Context:- This modules build over the core and represent the advance implementation of IOCcontainer.TX (Transaction Management):-This modules build over the AOP and provide facility tomanage transaction in spring.JDBC:-This modules build over the TX modules and provide template implementation of JDBC.
  61. 61. ORM (Object Relation Mapping):-This modules build over the JDBC that provide the facilityof integration spring application to ORM framework such as Hibernate , Toplink etcWeb:-This module is build over context provide automation of common operation of webapplication such as transfer of request ,data to domain object ,file uploading ,tiles conventionetc.Web MVC:-This module build over the web and provide an MVC implementation of spring fordeveloping web application.Struts Integration:-This module build over the web and provide facility to integrate springapplication to struts.Enterprise Integration:-This module provide facility of integration enterprise services such asJNDI ,JMS ,Java Mail ,Web Services etc. to Spring application.Testing:-This module over the core and provide the facility of unit an integration of testing.1.4 .Concept of Spring Framework :-The Spring Framework work in two concept which arefollowing:- A. IOC (Inversion of Control) B. AOP (Aspect Oriented Programming)Inversion of Control (IOC):- The inversion of control (IOC) provide the facility to creation ofobject ,dependency satisfaction and lifecycle management.Aspect Oriented Programming (AOP):-The Aspect Oriented Programming (AOP) provide theconcept of cross-cutting concern. The cross-cutting concern first one is concern , the concern isa task that perform as part of an operation and second one is cross-cutting, the cross-cutting isa set of concern that participate multiple operation. 2. IOC Concept of Spring Framework2.1 .Introduction :-The spring framework work the concept inversion of control , this conceptprovide the facility to create an object ,satisfied the dependency and lifecycle management. Inthe case of conventional approach creation of an object ,dependency satisfaction and lifecyclemanagement all of these task are responsible for application developer.Problem associated with conventional usage of an object:-1. An application developer need to focus on object creation ,dependency satisfaction andlifecycle management in addition to object usage.2. Conventional method create tight coupling between object and there user. The tight couplingalways create maintenance problem.3. Conventional approach result in memory wastage because each user creates own objectwhich prevent object reusability. IOC propose the runtime environment called IOC container that should be used by theapplication developer to request object. If creation of an object their dependency satisfactionand lifecycle management is manage by IOC container then application developer can focus on
  62. 62. used to object. Object can be shared among and loose coupling between object and user can beprovided. Following two approach are used to provide the Implementation of IOC. A. Dependency Injection B. Dependency Lookup2.2 .Dependency Injection (DI):-In case of DI (Dependency Injection) ,dependency of objectare satisfied by IOC container on its own i.e IOC container are not ask to satisfied thedependency of an object.2.3 .Dependency Lookup (DL):-In case of DL (Dependency Lookup) ,dependency of an objectare satisfied only when IOC container is asked to do so.Note:-The spring framework does not support dependency lookup (DL) only supportdependency injection (DI) approach. 3. Terminology of Spring Framework3.1 .Bean :-Bean definition object represented by the XmlBeanFactory(DefaultListableBeanFactory). the bean manage object creation ,dependency satisfactionthrough the IOC container which contain following details:-the <bean> element is used to specify the configuration of a bean to IOC container. the syntaxof <bean > element.<bean id="UniqueIdentifier" name="alias" class="BeanClass" scope="singleton/prototype"factory-method="Name of factory method" factory-bean="Name of factory bean">3.2 .Bean Tag Element:-There are many types of bean tag element in the spring frameworkwhich are following:-1. id and name:-The bean identify in which type of bean class are requested by the user.2. class:-The bean class provide the information of requested by user.3. singleton and prototype:-The bean create object one time in the case of singleton and beancreate object requirement of user it means more then one time in the case of proto type.4. constructor argument:-This configuration provide value in constructor of the bean class ifwhich are defined in bean class. This configuration used in constructor injection.5. property bean:-This configuration set the value in setter method which are define in the beanclass. This configuration used in setter injection.3.3 .Identify Bean by IOC container:-IOC container usage id, name and class attribute issame sequence to identify a bean. 3.4 .Resource:-Resource is an interface provided by the framework it contain method formanaging configuration information. The configuration information represent informationrequired by IOC container for creating ,dependency satisfaction and lifecycle management ofbean.
  63. 63. 3.5 .BeanFactory:-BeanFactory is an interface provided by spring framework . This interfacerepresent the functionality of basic IOC container . Implementation of it is provided by theframework. 4. Hello World Example in Spring FrameworkIntroduction:-The Hello world example in spring framework uses the constructor injection. Itmeans that object is created by the IOC container through the constructor.Class/Library File Descriptions:-First of all we are create bean class name Hello then definethe parameterize constructor and define a method name display which are print string sandedby configuration XML file.Configuration information syntax:-<bean id="hello" class="org.r4r.Hello"><constructor-arg value="Hello World !"/></bean>Technologies used to run this source code:- 1. Spring 2.5 2. Eclipse 3. JDK 1.6Source Code:- applicationContext.xml<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="hello" class="org.r4r.Hello"><constructor-arg value="Hello World !"/></bean></beans> Hello.javapackage org.r4r;public class Hello { String hello; public Hello(String hello) { super(); this.hello = hello; } public void display(){
  64. 64. System.out.println(hello); }} HelloTest.javapackage org.r4r;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;public class HelloTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); Hello h=(Hello)f.getBean("hello"); h.display(); }}OutPut:-Hello World ! 5.Creation of an Object in Spring Framework5.1 .Introduction :-In the Spring Framework provide the concept IOC container which areresponsible for creation of an object, satisfied the dependency and lifecycle management. Firsttask of the IOC container is creation of an objects. Objects can be create through constructorand factory method. By default IOC container create object using constructor. In order to facilitateobject creation using factory method. Information of the factory need to be provided.5.2 .Type of Object Creation :-In the spring framework concept IOC container which arecreate an object following two type a. Using Constructor b. Using Factory Method5.3 .Object Creation Using Constructor :-IOC container create object through theconstructor, If we are creating object through IOC container first you are declare parameterizeconstructor in our bean class and define method to print any message through the configurationfile. The following syntax used in configuration file if we are create object through theconstructor
  65. 65. <bean id="hello" class="org.r4r.Hello"><constructor-arg value="Hello World !"/></bean>5.4 .Object Creation Using factory method :-IOC container create object through thefactory method, If we are creating object throughIOC container first you are declare parameterize method in our bean class and print anymessage through the configuration file. The following syntaxused in configuration file if we are create object through the factory method.<bean id="number" class="org.r4r.Complex" factory-method="getNumber"scope="prototype"/>Factory method can be divided in following three way:-5.4.1. Same class static factory:- class A{ private(){ //Logic is written } public static A getA(){ return new A(); } }Following configuration need to provided to the IOC container to use getA() factory method.<bean id="a" class="A" factory-method="getA"/>5.4.2. Different class static factory:- class B{ { == } class A{ //Different class static factory public static B getB(){ return new B();
  66. 66. } }Following configuration need to provided the IOC container to use getB() factory method.<bean id="b" class="A" factory-method="getB"/>5.4.3. Different class non-static factory:- class B{ { == } class A{ //Different class nonstatic factory public B getB(){ return new B(); } }Following configuration need to provide the IOC container to use getB() factory method.<bean id="a" class="A"/><bean id="b" class="B" factory-method="getB" factory-bean="a"/> 6.Object Create Example Using ConstructorIntroduction:-This example will used to create object through the constructor and print "ThisObject is created by constructor".Technology use to run this source code:- 1. Spring 2.5 2. Eclipse 3. JDK 1.6Source Code:- applicationContext.xml
  67. 67. <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="constructorBean" class="org.r4r.ConstructorExample"><constructor-arg value="This message is generated by Constructor."/></bean></beans> ConstructorExample.javapackage org.r4r;public class ConstructorExample { String message; public ConstructorExample(String message) { super(); this.message = message; } public void display(){ System.out.println("This message is generated by method."); System.out.println(message); }} ConstructorTest.javapackage org.r4r;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;public class ConstructorTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); ConstructorExample e=(ConstructorExample)f.getBean("constructorBean"); e.display(); }}
  68. 68. OutPut:-This message is generated by method.This message is generated by Constructor. 7.Object Create Example Using Same Class Static FactoryIntroduction:-This example will used to create object through the same class static factoryand print "Number you are enter and sum of number which are enter by you".Technology use to run this source code:- 1. Spring 2.5 2. Eclipse 3. JDK 1.6Source Code:- applicationContext.xml<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="number" class="org.r4r.NumberDisplay" factory-method="getNumber"scope="prototype"/></beans> NumberDisplay.javapackage org.r4r;import java.util.Scanner;public class NumberDisplay { int a,b; public NumberDisplay(int a, int b) { super(); this.a = a; this.b = b; } public static NumberDisplay getNumber(){ Scanner in=new Scanner(System.in); System.out.println("Enter the first number:-");
  69. 69. int x=in.nextInt(); System.out.println("Enter the second number:-"); int y=in.nextInt(); return new NumberDisplay(x,y); } public void display(){ System.out.println("You are enter first number is:-t"+a); System.out.println("You are enter second number is:-t"+b); int x=a+b; System.out.println("Sum of both number is:-"+x); }} NumberTest.javapackage org.r4r;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;public class NumberTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining numbers from the IOC Container..."); NumberDisplay n1=(NumberDisplay)f.getBean("number"); n1.display(); }}OutPut:-Obtaining numbers from the IOC Container...Enter the first number:-9876Enter the second number:-6789You are enter first number is:- 9876You are enter second number is:- 6789Sum of both number is:-16665 8.Object Create Example Using Different Class Static FactoryIntroduction:-This example will used to create object through the different class static factoryand print "Number you are enter and sum of number which are enter by you".Technology use to run this source code:-

×