Very Important Example of Hibernate3.0
Very Important Example of Hibernate3.0
5/
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 -
<!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:-
Step5:-
//PersistTest.java
package 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 application developer:
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.
2- Create Emp.java class:package r4r; public class Emp { int id; String name,job; int salary;
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; }
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>
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(); } }
save():method of Session interface is used to persist object. public void save (Object o);
refresh():is used to Synchronized the state of a persistaent logc to the database. public void refresh(Object o);
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 of generator. 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.
2-Sequence Generator:sequence gnerator uses the sequence define in the database for generating id.
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 ways1- Table per class Hierarchy 2- Table per subclass 3- Table per class
1- Table Per Class Hierarchy:- In this approach objects of all the classes of a family are
mapped to a single table in a database. This table contain field to represent combined data member of all the classes of the family plus an additional fields is used to describe record of the table ,that is, to identified which record of table represent object of which class of the family
Advantages Of This Approach:Major advantages of this approach is performance. Because hibernate need to manage toall the classes to the family.
Disadvantages Of This Approach:1-Table is not normalized 2-Not Null constraint can not be applied non the field representing data member of subclass
2-Table Per Subclasses:In this approach one table for each class of the faimily is created. Table for the parent class contains field to represenent parent class data member and table for the subclasses contains fields to represent their own data member. Primary key of parent table is used for hierarchy in table for subclasses.
Advantages
Disadvantages:
performance is degraded becouse to insert and fetched subclsses object .Multiple queries or joins are required Tables are not fully normalized.
3-Table Per Class:In this approach one table for each class of the family is created. Each table contains fields 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 waysIn case of unidirectional:1- Using primary key-foreign key relation 2- Using same primary Key 3-Using relation table
Disadvantages:This approach can only be used if relation between objects which be one to one .If in future
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 there are three 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> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="PkFk.hbm.xml"/> </session-factory> </hibernate-configuration>
//Address.java
package r4r; public class Address { int id; String city,street; public Address() { } public Address(String city, String street) { super(); this.city = city; this.street = street;
} 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.java
package 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; } }
//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.java
package r4r; import import import import org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.Transaction; 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);
2-Same Primary Key Mapping:In this approach owner and owned shared same primary key value.
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">
<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 used 1- 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>
</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> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="listAndBag.hbm.xml"/> </session-factory> </hibernate-configuration>
// Batch.java
package 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.java
package r4r; import java.util.*;
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.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(); } }
//PersisTest.java
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 relation object 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 using inwards 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 many privileges and many employee can get a single privileges. So here is an many-to-many mapping
//Emp.java
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
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>
<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.java
package 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();
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 oriented way 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 called Hibernate Query Language(HQL).
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.Query 2-Customize the Query object 3-Execute the Query
Step 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 ,cache mode , 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 or uniqueResult().
from classname as Alias ex1- 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 condition ex- To fetch all those employee who earn more 75000/month from Emp e where e.salary>75000
3-To fetch name of all manager select e.name from Emp e where e.job="manager"
Note:HQL queries supports named as well as positioned parameters First Approach:-(positioned parameter):Query q=session.createQuery("select e.name from Emp e e.job=?"); q.setString(1,job); // value of positioned parameter is set. Second Approach(Named parameter):Query q=session.createQuery("from Emp e where e.salary>:salary"); q.setInt("salary",s);
<?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>
} 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.java
package 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();
System.out.println(emp.getName()+"\t"+emp.getSalary()); } session.close(); } }
<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="Student.hbm.xml"/> </session-factory> </hibernate-configuration>
Student.java
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"/> -->
</class> </hibernate-mapping>
package mypack; import java.util.Iterator; import java.util.List; import import import import org.hibernate.Query; org.hibernate.Session; org.hibernate.SessionFactory; 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 object temporally in the memory . The purpose of caching to improve the performance by reducing database hits . If same object is required by different session or user then it make sense to fetch them only one and to store them into the cache so that they can provide the cache each time they are requested.
Hibernate support caching at two levels:1- First Level Caching 2-Second Level Caching
First Level Caching :-(Transactional scope caching):First level caching is implicitly enable. It is implemented by session . Fist level caching is responsible for storing the object used by user.Object in this cache has transactional scope, once the transaction is completed object of this cache are synchronize to the database and cache is discarded.
Second Level Cache (Application Scope caching):Second level cache is not enable by default. This cache has a application scope, Object in this cache are shared by multiple users. This cache is managed by sessionFactory
NOTE:-
provide specification how second level cache should be implemented. Third party implementation of second level cache are available:
Hibernate Specification says that cache provider must defined block in memory for storing 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 Cache:In object ache ,object along with there relation are stored in Simplified Form.
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 memory
1- In first reason query along with the value of parameter to stored as key and id of
returned object are stored as value. 2- In second region time stamp of query execution is stored. The Purpose of this region is to identified whether result of query is valid or not
Program Of EHCache:Example: This example shows the implementation of EHCache 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="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> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="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>
</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;
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;
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();
} }
S2Test.java:package r4r; import import import import java.util.*; org.hibernate.*; org.hibernate.cfg.Configuration; 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);
} }
<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="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> -->
</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; } }
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 import import import org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.Transaction; 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(); 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.
} public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
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; } }
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 hibernate 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> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="personal.hbm.xml"/> </session-factory> </hibernate-configuration>
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">
<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 import import import import import java.io.IOException; java.io.PrintWriter; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;
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);
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/javaee http://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>
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> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="Registration.hbm.xml"/> </session-factory> </hibernate-configuration>
Registration.java
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; }
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.java
package mypack; import import import import org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.Transaction; 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>
</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 Configuration 2.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.java
package 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.5 51.How can integrate Struts 2.x and Spring Framework
51.1.Introduction:-The Struts 2.x is the web application framework in Java Technology, this framework provide the concept of Model View Controller (MVC) and Interceptor to develop the web application. The Spring framework provide the facility to integrate with other framework and Developed the application in java. This tutorial provide the facility how can integrate between 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.x
framework:-
Step 1:-First select the web project in our IDE and add the capability of spring 2.5 and Struts 2.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 configuration information. Step 4:-Also create applicationContext.xml in WEB-INF folder to give the spring configuration information. 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.
<?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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Struts2Example14</display-name> <filter>
<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
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
OutPut:-
1. Introduction of Spring Framework 2.5 1.1 .Introduction :-The Spring Framework is a lightweight open source application framework that provide 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 framework does 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 following modules.
ORM (Object Relation Mapping):-This modules build over the JDBC that provide the facility of integration spring application to ORM framework such as Hibernate , Toplink etc Web:-This module is build over context provide automation of common operation of web application such as transfer of request ,data to domain object ,file uploading ,tiles convention etc. Web MVC:-This module build over the web and provide an MVC implementation of spring for developing web application. Struts Integration:-This module build over the web and provide facility to integrate spring application to struts. Enterprise Integration:-This module provide facility of integration enterprise services such as JNDI ,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 are following:A. IOC (Inversion of Control) B. AOP (Aspect Oriented Programming) Inversion of Control (IOC):- The inversion of control (IOC) provide the facility to creation of object ,dependency satisfaction and lifecycle management. Aspect Oriented Programming (AOP):-The Aspect Oriented Programming (AOP) provide the concept of cross-cutting concern. The cross-cutting concern first one is concern , the concern is a task that perform as part of an operation and second one is cross-cutting, the cross-cutting is a set of concern that participate multiple operation.
used to object. Object can be shared among and loose coupling between object and user can be provided. Following two approach are used to provide the Implementation of IOC. A. Dependency Injection B. Dependency Lookup 2.2 .Dependency Injection (DI):-In case of DI (Dependency Injection) ,dependency of object are satisfied by IOC container on its own i.e IOC container are not ask to satisfied the dependency of an object. 2.3 .Dependency Lookup (DL):-In case of DL (Dependency Lookup) ,dependency of an object are satisfied only when IOC container is asked to do so. Note:-The spring framework does not support dependency lookup (DL) only support dependency injection (DI) approach.
3.5 .BeanFactory:-BeanFactory is an interface provided by spring framework . This interface represent the functionality of basic IOC container . Implementation of it is provided by the framework.
<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.6 Source 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.java
package org.r4r; public class Hello { String hello; public Hello(String hello) { super(); this.hello = hello; } public void display(){
} }
System.out.println(hello);
HelloTest.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; 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 !
<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 the factory method, If we are creating object through IOC container first you are declare parameterize method in our bean class and print any message through the configuration file. The following syntax used 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.
5.4.2. Different class static factory:class B{ { == } class A{ //Different class static factory public static B getB(){ return new B();
} } Following configuration need to provided the IOC container to use getB() factory method.
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.
<?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.java
package 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.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; 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(); } }
<?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.java
package 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:-");
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.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; 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:9876 Enter the second number:6789 You are enter first number is:- 9876 You are enter second number is:- 6789 Sum of both number is:-16665
<?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.NumberFactory" factory-method="getNumber"/> </beans>
NumberFactory.java
package org.r4r; import java.util.Scanner; public class NumberFactory { public static NumberDisplay getNumber(){ Scanner in=new Scanner(System.in); System.out.println("Enter the first number:-"); int x=in.nextInt(); System.out.println("Enter the second number:-"); int y=in.nextInt(); return new NumberDisplay(x,y); } }
NumberDisplay.java
package org.r4r; public class NumberDisplay { int a,b; public NumberDisplay(int a, int b) { super(); this.a = a;
this.b = b; } 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.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; 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:9876 Enter the second number:6789 You are enter first number is:- 9876 You are enter second number is:- 6789 Sum of both number is:-16665
<?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="number1" class="org.r4r.NumberFactory"> <constructor-arg value="1"></constructor-arg> </bean> <bean id="number" factory-bean="number1" factory-method="getNumber" scope="prototype"></bean> </beans>
NumberFactory.java
package org.r4r; import java.util.Scanner; public class NumberFactory { static final int NumberDisplay=1; int number; public NumberFactory(int number) { super(); this.number = number; } public void getNumberFactory(){ number=NumberDisplay;
} public NumberDisplay getNumber(){ Scanner in=new Scanner(System.in); System.out.println("Enter the first number:-"); int x=in.nextInt(); System.out.println("Enter the second number:-"); int y=in.nextInt(); return new NumberDisplay(x,y); } }
NumberDisplay.java
package org.r4r; public class NumberDisplay { int a,b; public NumberDisplay(int a, int b) { super(); this.a = a; this.b = b; } 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.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; 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:9876 Enter the second number:6789 You are enter first number is:- 9876 You are enter second number is:- 6789 Sum of both number is:-16665
10.2.2 .Prototype Bean:-This bean provide the facility to request more then one bean if any user request bean then different bean provide each request. Syntax of Prototype bean:-
<?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.Complex" factory-method="getNumber" scope="singleton"/> </beans> Number.java
package org.r4r; public interface Number { public void display(); public Number add(Number n); } Complex.java
package org.r4r; import java.util.Scanner; public class Complex implements Number { int r,i; public Complex(int r, int i) { super(); this.r = r; this.i = i; } public static Number getNumber(){ Scanner in=new Scanner(System.in); System.out.println("Enter the rational part:-"); int x=in.nextInt(); System.out.println("Enter the imagenary part:-"); int y=in.nextInt(); return new Complex(x,y); } @Override public Number add(Number n) { Complex c=(Complex)n; int x=this.r+c.r; int y=this.i+c.i; return new Complex(x,y);
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class IocNumberUser { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining numbers n1 & n2 from the IOC Container..."); Number n1=(Number)f.getBean("number"); Number n2=(Number)f.getBean("number"); System.out.println("Number n1 is:"); n1.display(); System.out.println("Number n2 is:"); n2.display(); Number n3=n1.add(n2); System.out.println("Sum of n1 and n2"); n3.display(); } } OutPut:Obtaining numbers n1 & n2 from the IOC Container... Enter the rational part:5 Enter the imagenary part:6 Number n1 is: 5+6i Number n2 is: 5+6i Sum of n1 and n2 10+12i
Introduction:-The prototype bean is the optional bean of the scope attribute that provide the facility to the user create more then one object if you are requested more then one time the prototype bean provide per request new object of same bean.. Technology use to run this source code:1. Spring 2.5 2. Eclipse 3. JDK 1.6 Source 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.Rational" factory-method="getNumber" scope="prototype"/> </beans> Number.java
package org.r4r; public interface Number { public void display(); public Number add(Number n); } Rational.java
package org.r4r; import java.util.Scanner; public class Rational implements Number { int p,q; public Rational(int p, int q) { super(); this.p = p; this.q = q;
} public static Number getNumber(){ Scanner in=new Scanner(System.in); System.out.println("Enter the Numerator part:-"); int p=in.nextInt(); System.out.println("Enter the Denominator part:-"); int q=in.nextInt(); return new Rational(p,q); } @Override public Number add(Number n) { Rational r=(Rational)n; int x=this.p*r.q+this.q*r.p; int y=this.q*r.q; return new Rational(x,y); } @Override public void display() { System.out.println(p+"/"+q); } } IocNumberUser .java package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class IocNumberUser { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining numbers n1 & n2 from the IOC Container..."); Number n1=(Number)f.getBean("number"); Number n2=(Number)f.getBean("number"); System.out.println("Number n1 is:"); n1.display(); System.out.println("Number n2 is:"); n2.display(); Number n3=n1.add(n2); System.out.println("Sum of n1 and n2"); n3.display(); } } OutPut:-
Obtaining numbers n1 & n2 from the IOC Container... Enter the Numerator part:6 Enter the Denominator part:5 Enter the Numerator part:4 Enter the Denominator part:8 Number n1 is: 6/5 Number n2 is: 4/8 Sum of n1 and n2 68/40
13.Dependency Injection
13.1 .Introduction:-In case of DI (Dependency Injection) ,dependency of object are satisfied by IOC container on its own i.e IOC container are not ask to satisfied the dependency of an object. 13.2 .Approach of Dependency Injection:-There are two approach of Dependency Injection which are following:1. Constructor Dependency Injection 2.Setter Dependency Injection 13.2.1 .Constructor Dependency Injection:-In this approach the IOC container provide the facility to satisfied the dependency of an object in mandatory case and IOC container inject the dependency through the constructor. 13.2.1 .Setter Dependency Injection:- In this approach the IOC container inject the dependency through the default constructor and setter method. This approach is used in the case of optional dependency. 13.3 .Type of Dependency Injection:-There are three type of dependency injection which are following:1. Dependency on primitive values (String is consider primitive by String). 2. Dependency on Object. 3. Dependency on Collection. 13.3.1 .Dependency on primitive value:-In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specified the dependency of a bean i.e to be satisfied to a constructor this elements uses values and reference attribute which are used to specified value primitive type and object respectively. Syntax:<bean .................>
<constructor-arg value="primitive or String"/> <constructor-arg ref="Reference of a bean"/> ................ </bean> 13.3.2 .Dependency on object:-In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of an object i.e to be satisfied the constructor-arg element uses reference of an attribute which are used to specify object respectively. Syntax:<bean .................> <constructor-arg > <list><ref bean="Reference of a bean"/> ................ </list></constructor-arg> </bean> 13.3.2 .Dependency on collection:-In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied the constructor-arg element uses list ,set and map sub element to specify the dependency of list ,set and map respectively. Syntax:<bean .................> <constructor-arg > <list or set or map> <Value></value> ................ </list or set or map></constructor-arg> </bean>
Technology use to run this source code:1. Spring 2.5 2. Eclipse 3. JDK 1.6 Source 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="ab" class="org.r4r.A"> <constructor-arg value="101" /> <constructor-arg value="Mukund Singh" /> </bean> </beans> A.java
package org.r4r; public class A { int a; String b; public A(int a,String b) { super(); this.a=a; this.b =b; System.out.println("Constructor is invoked"); } public void display() { System.out.println(a+"\t\t"+b); } }
Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String ar[]){ Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Constructor value are following"); A a1=(A)f.getBean("ab"); a1.display(); } } OutPut:Constructor value are following Constructor is invoked 101 Mukund Singh
<?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="a1" class="org.r4r.A"/> <bean id="a2" class="org.r4r.A"> <constructor-arg value="10"/> </bean> <bean id="a3" class="org.r4r.A"> <property name="a" value="100"/> </bean> </beans> A.java
package org.r4r;
public class A { int a; public A(int a) { super(); this.a = a; System.out.println("A is instantiated using parameter constructor."); System.out.println("Value of a:-\t"+a); } public A() { super(); System.out.println("A is instantiated using Default constructor."); } public void setA(int a) { this.a = a; System.out.println("Value of A is set by setA() method."); System.out.println("Value of a:-\t"+a); } } Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); //A a1=(A)f.getBean("a1"); @SuppressWarnings("unused") A a2=(A)f.getBean("a2"); @SuppressWarnings("unused") A a3=(A)f.getBean("a3"); } } OutPut:A is instantiated using parameter constructor. Value of a:- 10 A is instantiated using Default constructor. Value of A is set by setA() method. Value of a:- 100
<?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.Dependency on primitive value examplespringframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="ab" class="org.r4r.A"> <constructor-arg value="101" /> <constructor-arg value="102" type="int"/> </bean> </beans> A.java
package org.r4r; public class A { int a; String b; public A(int a,String b) { super(); this.a=a; this.b =b; System.out.println("Constructor is invoked"); } public void display() { System.out.println(a+"\t\t"+b); } } Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String ar[]){ Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Constructor value are following"); A a1=(A)f.getBean("ab"); a1.display(); } } OutPut:Constructor value are following Constructor is invoked 102 101
<?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="c1" class="org.r4r.Course"> <constructor-arg value="MCA"/> <constructor-arg value="150000"/> </bean> <bean id="c2" class="org.r4r.Course"> <constructor-arg value="MBA"/> <constructor-arg value="250000"/> </bean>
<bean id="ab" class="org.r4r.Student"> <constructor-arg value="101"/> <constructor-arg value="Mukund"/> <constructor-arg> <set> <ref bean="c1"/> <ref bean="c2"/> </set> </constructor-arg> </bean> </beans> Course.java
package org.r4r; public class Course { String name; int fee; public Course(String name, int fee) { super(); this.name = name; this.fee = fee; } public String toString(){ StringBuffer b=new StringBuffer(); b.append(name).append("\t\t").append(fee); return b.toString(); } }
Student.java
package org.r4r; import java.util.Iterator; import java.util.Set; public class Student { int id; String n; Set<Course> course; public Student(int id, String n, Set<Course> course) { super(); this.id = id; this.n = n; this.course = course; } public String toString(){ StringBuffer b=new StringBuffer();
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String ar[]){ Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); Student a1=(Student)f.getBean("ab"); System.out.println("Student information is,"); System.out.println(a1); } } OutPut:Student information is, Name:Mukund Course details MCA 150000 MBA 250000
<?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="ab" class="org.r4r.Student"> <constructor-arg value="101"/> <constructor-arg value="Mukund"/> <constructor-arg> <list> <value>Core Java</value> <value>J2EE</value> <value>Struts</value> <value>Hibernate</value> <value>Spring</value> </list> </constructor-arg> </bean> </beans> Student.java
package org.r4r; import java.util.*; public class Student { int id; String n; List<String> course; public Student(int id, String n, List<String> course) { super(); this.id = id; this.n = n; this.course = course; } public String toString(){ StringBuffer b=new StringBuffer(); b.append("Name:\t\t").append(n).append("\n").append("Course details:\t\n"); Iterator<String> itr=course.iterator(); while(itr.hasNext()){ b.append(itr.next()).append("\n"); } return b.toString(); } } Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String ar[]){ Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); Student a1=(Student)f.getBean("ab"); System.out.println("Student information is,"); System.out.println(a1); } } OutPut:Student information is, Name: Mukund Course details: Core Java J2EE Struts Hibernate Spring
<?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="ab" class="org.r4r.Student"> <constructor-arg value="101"/>
<constructor-arg value="Mukund"/> <constructor-arg> <set> <value>Core Java</value> <value>J2EE</value> <value>Struts</value> <value>Hibernate</value> <value>Spring</value> </set> </constructor-arg> </bean> </beans> Student.java
package org.r4r; import java.util.*; public class Student { int id; String n; Set<String> course; public Student(int id, String n, Set<String> course) { super(); this.id = id; this.n = n; this.course = course; } public String toString(){ StringBuffer b=new StringBuffer(); b.append("Name:\t\t").append(n).append("\n").append("Course details:\t\n"); Iterator<String> itr=course.iterator(); while(itr.hasNext()){ b.append(itr.next()).append("\n"); } return b.toString(); } }
Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String ar[]){ Resource r=new ClassPathResource("applicationContext.xml");
OutPut:Student information is, Name: Mukund Course details: Core Java J2EE Struts Hibernate Spring
<?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="ab" class="org.r4r.Institute"> <constructor-arg value="XYZ"/> <constructor-arg> <map> <entry key="MCA" value="150000"/> <entry key="MBA" value="250000"/> <entry key="BCA" value="50000"/> <entry key="BBA" value="100000"/> </map> </constructor-arg> </bean> </beans>
Institute.java
package org.r4r; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Institute { String name; Map<String, String> courseDetails; public Institute(String name, Map<String, String> courseDetails) { super(); this.name = name; this.courseDetails = courseDetails; } public void display(){ System.out.println("Name:\t"+name); System.out.println("Course Name\t\tFee"); Set<Map.Entry<String, String>> set=courseDetails.entrySet(); Iterator<Map.Entry<String, String>> itr=set.iterator(); while(itr.hasNext()){ Map.Entry<String, String> m=itr.next(); System.out.println(m.getKey()+"\t\t"+m.getValue()); } } }
Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String ar[]){ Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Constructor value are following"); Institute a1=(Institute)f.getBean("ab"); a1.display(); } } OutPut:Constructor value are following
Name: XYZ Course Name Fee MCA 150000 MBA 250000 BCA 50000 BBA 100000
<?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="a1" class="org.r4r.Institute"> <property name="name" value="HIMT"/> <property name="courseDetail"> <map> <entry key="MCA" value="75000"/> <entry key="MBA" value="175000"/> <entry key="BCA" value="50000"/> <entry key="BBA" value="50000"/> </map> </property> </bean> </beans> Institute.java
package org.r4r; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Institute {
String name; Map<String, String> courseDetail; public void setName(String name) { this.name = name; } public void setCourseDetail(Map<String, String> courseDetail) { this.courseDetail = courseDetail; } public void display(){ System.out.println("Name:-\t"+name); System.out.println("\nCourse Details:-"); Set<Map.Entry<String, String>> set=courseDetail.entrySet(); Iterator<Map.Entry<String, String>> itr=set.iterator(); while(itr.hasNext()){ Map.Entry<String, String> m=itr.next(); System.out.println(m.getKey()+"\t"+m.getValue()); } } }
Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); Institute i=(Institute)f.getBean("a1"); i.display(); } }
OutPut:Name:- HIMT Course Details:MCA 75000 MBA 175000 BCA 50000 BBA 50000
22.1 .Introduction of an Autowiring:- An autowiring is the facility provided by framework to satisfied by dependency of manage bean without configuration information. It means that the autowiring solved problem to write very long configuration information. 22.2 .Type of method to Autowire:- The following four method are used by IOC container to autowire bean dependency. 1.Autowire by Type 2.Autowire by Name 3.Autowire by Constructor 4.Autowire by autodetect 22.2.1 .Autowire by Type:-In autowiring by type , The IOC container used the bean property by type to identified the beans to be injected i.e in order to used autowiring by type we need to simply configure one bean for each property of the target bean. Note:- Facility of autowiring are used only with object type dependency i.e primitive dependency are note autowire. Syntax:<bean id="x" class="org.r4r.A"/> <bean id="b" class="org.r4r.B" autowire="byType"/> Disadvantage of Autowire:1. Optional dependency are specified using by type because dependency are injected by setter method. 2. Autowiring by type can not be used if there are more than one beans. Configured for a properties type. 22.2.2 .Autowire by Name:-In this case IOC container uses the name of a bean property to fined out the bean for injecting i.e in this approach the configuration bean to be used for satisfied the dependency of the bean must have the same as the bean property. Syntax:<bean id="a" class="org.r4r.A"/> <bean id="y" class="org.r4r.A"/> <bean id="b" class="org.r4r.B" autowire="byName"/>
Disadvantage of Autowire:1. Only optional dependency can be autowire for this approach. 2. This approach would work of a bean of different type is configure using the same name as the property of a bean which uses autowiring.
22.2.3 .Autowire by Constructor:-In this approach type of parameter of the constructor are used to identified the bean to be injected in case of overloaded constructed has a maximum parameter will choose. This approach is same as autowiring by type accept dependency are injected through constructor in it. Syntax:<bean id="a" class="org.r4r.A"/> <bean id="b" class="org.r4r.B" autowire="constructor"/> 22.2.4 .Autowire by Autodetect:-This approach is a combination of autowiring by constructor and autowiring by type in it dependency is injected using the type of property if target bean has a default constructor and dependency are injected using constructor injection if target bean has a parameterize constructor. Note:-This is the default strategy of the autowiring. <bean id="x" class="org.r4r.A"/> <bean id="b" class="org.r4r.B" autowire="autodetect"/> 22.3 .Limitation of Autowiring:Major draw back of autowiring is understandability is loosed
<?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="a" class="org.r4r.A"/> <bean id="y" class="org.r4r.A"/> <bean id="b" class="org.r4r.B" autowire="byName"/> </beans>
A.java
package org.r4r; public class A { public A() { super(); System.out.println("A is instantiated"); } } B.java
package org.r4r; public class B { A a; A y; public B() { super(); System.out.println("Default constructor of B is invoked."); } public B(A a) { super(); this.a = a; System.out.println("Parameterized constructor of B is invoked."); } public void setA(A a) { this.a = a; System.out.println("setA() method is invoked typeName a."); } public void setY(A y) { this.y = y; System.out.println("setA() method is invoked typeName y."); }
Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); @SuppressWarnings("unused") B b=(B)f.getBean("b"); }
OutPut:Default constructor of B is invoked. A is instantiated A is instantiated setA() method is invoked typeName a. setA() method is invoked typeName y.
<?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="x" class="org.r4r.A"/> <bean id="b" class="org.r4r.B" autowire="byType"/> </beans> A.java
B.java
package org.r4r; public class B { A a; public B() { super(); System.out.println("Default constructor of B is invoked."); } public B(A a) { super(); this.a = a; System.out.println("Parameterized constructor of B is invoked."); } public void setA(A a) { this.a = a; System.out.println("setA() method is invoked."); } } Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); @SuppressWarnings("unused") B b=(B)f.getBean("b"); } } OutPut:Default constructor of B is invoked. A is instantiated setA() method is invoked.
<?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="a" class="org.r4r.A"/> <bean id="b" class="org.r4r.B" autowire="constructor"/> </beans> A.java
package org.r4r; public class A { public A() { super(); System.out.println("A is instantiated"); } } B.java
package org.r4r; public class B { A a; A y; public B() { super(); System.out.println("Default constructor of B is invoked."); }
public B(A a) { super(); this.a = a; System.out.println("Parameterized constructor of B is invoked."); } public void setA(A a) { this.a = a; System.out.println("setA() method is invoked typeName a."); } public void setY(A y) { this.y = y; System.out.println("setA() method is invoked typeName y."); } } Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); @SuppressWarnings("unused") B b=(B)f.getBean("b"); } } OutPut:A is instantiated Parameterized constructor of B is invoked.
Source 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="x" class="org.r4r.A"/> <bean id="b" class="org.r4r.B" autowire="autodetect"/> </beans> A.java
B.java
package org.r4r; public class B { A a; A y; public B() { super(); System.out.println("Default constructor of B is invoked."); } public B(A a) { super(); this.a = a; System.out.println("Parameterized constructor of B is invoked."); } public void setA(A a) { this.a = a; System.out.println("setA() method is invoked typeName a."); } public void setY(A y) {
Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); @SuppressWarnings("unused") B b=(B)f.getBean("b"); }
OutPut:Default constructor of B is invoked. A is instantiated setA() method is invoked typeName a. setA() method is invoked typeName y.
27.3 .Intrusive approach:-In the intrusive approach initialization bean interface provided by the framework is implemented in the bean class and initializing logic is contain with it after property set method. This method is provided by "InitializingBean" interface. 27.3.1 .InitializingBean:- The InitializingBean interface provide cleanup operation at the time of unloading of a bean either destroy-method attribute of bean is used. This interface provide a method name which are following:public void afterPropertiesSet(); Syntax:<bean id="one" class="org.r4r.One" destroy-method="init"/>
27.3.2 .DisposableBean:- This bean interface is provided by framework is implemented. This interface provide a method name destroy() if is invoked by IOC container before unload by IOC container before unloaded bean. This interface provide single method name destroy(). public void destroy();
<?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="one" class="org.r4r.One" init-method="init"/> <bean id="two" class="org.r4r.Two" init-method="init" destroy-method="cleanUp"/> </beans>
One.java
package org.r4r; import org.springframework.beans.factory.DisposableBean; public class One implements DisposableBean { @Override public void destroy() throws Exception { System.out.println("One is given a chance to performed cleanup operation"); } public One(){ System.out.println("One is instantiated..."); } public void init(){ System.out.println("One is given a chance to initialize"); } } Two.java
package org.r4r; import org.springframework.beans.factory.InitializingBean; public class Two implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("Intrusive initialization of two"); } public Two(){ System.out.println("Two is instantiated...."); } public void init(){ System.out.println("Nonintrunsive initialization of two...."); } public void cleanUp(){ System.out.println("Non-intrunsive cleanup of two..."); } } Test.java
import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining bean one..."); One one=(One)f.getBean("one"); f.isSingleton("one"); } } OutPut:Obtaining bean one... One is instantiated... One is given a chance to initialize Obtaining bean two... Two is instantiated.... Intrusive initialization of two Nonintrunsive initialization of two....
<?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="one" class="org.r4r.One" init-method="init"/> <bean id="two" class="org.r4r.Two" init-method="init" destroy-method="cleanUp"/> </beans>
One.java
package org.r4r; import org.springframework.beans.factory.DisposableBean; public class One implements DisposableBean { @Override public void destroy() throws Exception { System.out.println("One is given a chance to performed cleanup operation"); } public One(){ System.out.println("One is instantiated..."); } public void init(){ System.out.println("One is given a chance to initialize"); } } Two.java
package org.r4r; import org.springframework.beans.factory.InitializingBean; public class Two implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("Intrusive initialization of two"); } public Two(){ System.out.println("Two is instantiated...."); } public void init(){ System.out.println("Nonintrunsive initialization of two...."); } public void cleanUp(){ System.out.println("Non-intrunsive cleanup of two..."); } } Test.java
import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining bean one..."); @SuppressWarnings("unused") One one=(One)f.getBean("one"); System.out.println("Obtaining bean two..."); @SuppressWarnings("unused") Two two=(Two)f.getBean("two"); f.isSingleton("one"); //f.isPrototype("two"); } } OutPut:Obtaining bean one... One is instantiated... One is given a chance to initialize Obtaining bean two... Two is instantiated.... Intrusive initialization of two Nonintrunsive initialization of two....
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="b" class="org.r4r.Burger" scope="prototype"/> <bean id="a" class="org.r4r.Attendant" > </bean> </beans> Burger.java
package org.r4r; public class Burger { static int burgerCounter; int burgerNo; public Burger(){ burgerCounter++; burgerNo=burgerCounter; System.out.println("New burger is created..."); } public String toString(){ return "It is burger number:-"+burgerNo; } } Attendant.java
package org.r4r; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; public class Attendant implements BeanFactoryAware{ BeanFactory beanfactory; /*In this approach same Burger provided by Attendant * Then solved this approach after commented code * Burger burger; public Attendant(Burger burger) { super(); this.burger = Burger; System.out.println("Attendant bean is created..."); } public Burger getBurger(){ return burger; }*/ @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { beanfactory=beanFactory;
System.out.println("Reference of IOC container is provided to attendant."); } public Attendant() { System.out.println("Attendant bean is created..."); } public Burger getBurger(){ return (Burger)beanfactory.getBean("b"); } }
Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining attendant bean...."); Attendant a=(Attendant)f.getBean("a"); System.out.println("Requesting two burger....."); Burger b1=a.getBurger(); System.out.println(b1); Burger b2=a.getBurger(); System.out.println("Description of second burger..."); System.out.println(b2); } } OutPut:Obtaining attendant bean.... Attendant bean is created... Reference of IOC container is provided to attendant. Requesting two burger..... New burger is created... It is burger number:-1 New burger is created... Description of second burger... It is burger number:-2
31.1 .Introduction:-Spring 1.1 introducing method injection for a new IOC-Oriented feature with allows greater flexibility for interactions between collaborators. 31.2 .Type of Method Injection:The spring framework method injection provide this facility in to two way:1.Lookup Method Injection 2.Method replacement 31.3 .Lookup Method Injection:-The lookup method injection provide the facility to implement in our application one bean is depends on another bean with a different life cycle. It means that singleton bean depends on non-singleton bean. In this situation setter and constructor injection create instance of singleton bean not a non-singleton bean. In some case application require singleton bean obtain new instance of the non-singleton every time it requires the bean. If we achieve this implementation in our application the implement BeanFactoryAware interface in our singleton bean. Then using BeanFactory instance, the singleton bean can lookup a new instance of a non-singleton dependency every time it needs it. The Lookup Method Injection allows the singleton bean to declare that it requires a non-singleton dependency and receive a new instance of the non-singleton bean each time it needs to interact with it, without needing to implement any spring-specific interfaces. 31.4 .Method Replacement:-This Method injection provide a facility to replace the implementation of any method on a bean arbitrary, without changing our source code. Note:-If we are use lookup method injection and method replacement in our application, the add the CGLIB jar file in our application.
<?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="b" class="org.r4r.Burgar" scope="prototype"/> <bean id="na" class="org.r4r.NewAttendant" > <lookup-method bean="b" name="getBurgar"/> </bean> </beans> Burgar.java
package org.r4r; public class Burgar { static int burgarCounter; int burgarNo; public Burgar(){ burgarCounter++; burgarNo=burgarCounter; System.out.println("New burgar is created..."); } public String toString(){ return "It is burger number:-"+burgarNo; } } NewAttendant.java
package org.r4r; public abstract class NewAttendant { public abstract Burgar getBurgar(); } Test.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining attendent bean...."); NewAttendant a=(NewAttendant)f.getBean("na"); System.out.println("Requesting two burgar....."); Burgar b1=a.getBurgar(); System.out.println(b1); Burgar b2=a.getBurgar(); System.out.println("Discription of second burgar..."); System.out.println(b2); } } OutPut:Obtaining attendent bean.... Requesting two burgar..... New burgar is created... It is burger number:-1 New burgar is created... Discription of second burgar... It is burger number:-2
Concerns can be divided in to multiple category such as:1.Implementation Concern 2.Business Concern 3.Organization Concern etc. 1.Implementation Concern:- Implementation Concerns represents those task which are required before implementing for example:-Validation, Authorization, etc 2.Business Concern:- Business concern represent actual logic or main task of an operation. 3.Organization Concern:- Organization concern represent additional services, facility and requirement associated an operation by an organization. 33.4.What is Weaving in Spring AOP:The process of inserting advices is called weaving. Different AOP framework supports either weaving types:1.Compilation time weaving 2.Runtime weaving 1.Compilation time Weaving:- In Compilation time weaving advices are inserted at the time of Compilation at the special AOP compiler. Advantage:- The major advantage of this approach are performance. Disadvantage:- Special AOP compiler are required and application need to be recompile. 2.Runtime Weaving:- In this approach advices are dynamically inserted which the help of proxy object. Advantage:- Special AOP compiler are not required and Application are not required to be modified or recompile each time . Number of concerns or order changed. Disadvantage:- Performance are degrade because of additional overhead are proxy. Note:-A Spring AOP support Runtime weaving.
There are two type of Proxy Object in the Spring Framework:1.Static Proxy 2.Dynamic Proxy 34.3.Static Proxy:-Static Proxy are created by the developer at the time of development. Static Proxy develop in two way first through the developer and second through the used of any tools for example RMI compiler etc. 34.4.Dynamic Proxy:-Dynamic proxy are created at runtime. It is provided more flexibility. 34.5.Type of Dynamic Proxy:-There are two types of Dynamic Proxy in Spring Framework:1.JDK Dynamic Proxy 2.CGLIB Dynamic Proxy 34.6.JDK Dynamic Proxy:-JDK Dynamic Proxy is the facility provided by Sun micro System. In Reflection API to create dynamic proxy can not be created of those classes which implements some interface that is JDK dynamic proxy to implemented those method which are described by this interface implemented by target class. A JDK Dynamic proxy represent in instance dynamic proxy class which extends java.leng.reflect proxy class implemented by the target class. JDK dynamic proxy uses on Object. 34.7.CGLIB Dynamic Proxy:-CGLIB dynamic proxy is proxy of all the method of class perspective of the interface are implemented by the class.
package org.r4r; public class A implements Printable { @Override public void print() { System.out.println("print() mathod of A is invoked.."); } }
Printable.java
package org.r4r; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class PrintHandler implements InvocationHandler { Object target; public PrintHandler(Object target) { super(); this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Handler invoked invoking\t"+method.getName()+"() one target object.....");
//advices can be inserted here before actual method call. Object r=method.invoke(target, args); //advices can be inserted here after actual method call. System.out.println("Method call completed, returning value\t"+"return by actual method"); } } ProxyTest.java return r;
package org.r4r; import java.lang.reflect.Proxy; public class ProxyTest { public static void main(String[] args) { try{ System.out.println("Creating target object....."); A target=new A(); System.out.println("Creating handler...."); PrintHandler handler=new PrintHandler(target); System.out.println("Creating proxy,,,"); Printable proxy=(Printable)Proxy.newProxyInstance (target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler); System.out.println("invoking print() on proxy....."); proxy.print(); }catch(Exception e){ System.out.println(e); } } } OutPut:Creating target object..... Creating handler.... Creating proxy,,, invoking print() on proxy..... Handler invoked invokingprint() one target object..... print() mathod of A is invoked.. Method call completed, returning valuereturn by actual method
36.2 .Technology use to run this source code:1.Spring2.5 jar file 2.Eclips Id 3.Tomcat Server Note:-In this example take two different package in src folder our Application. First package name is org.r4r.framework and second package name is org.r4r.client. 36.3 .Source 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="t" class="org.r4r.client.One"/> <bean id="a" class="org.r4r.client.BeforeOne"/> <bean id="proxy" class="org.r4r.framework.ProxyFactory"> <property name="target" ref="t"/> <property name="advisor" ref="a"/> </bean> </beans> BeforeAdviceHandler.java
package org.r4r.framework; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class BeforeAdviceHandler implements InvocationHandler { Object target; BeforeMethod advisor; public BeforeAdviceHandler(Object target, BeforeMethod advisor) { super(); this.target = target; this.advisor = advisor; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { advisor.doBefore(); return method.invoke(target, args);
} } BeforeMethod.java
package org.r4r.framework; import java.lang.reflect.Proxy; import org.springframework.beans.factory.FactoryBean; public class ProxyFactory implements FactoryBean { Object target; BeforeMethod advisor; @Override public Object getObject() throws Exception { BeforeAdviceHandler handler=new BeforeAdviceHandler(target, advisor); Object proxy=Proxy.newProxyInstance (target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler); return proxy; } @Override public Class<Proxy> getObjectType() { return Proxy.class; } @Override public boolean isSingleton() { return true; } public void setTarget(Object target) { this.target = target; } public void setAdvisor(BeforeMethod advisor) { this.advisor = advisor; }
} One.java
package org.r4r.client; public class One implements Showable { @Override public void show() { System.out.println("Show() method of One invoked.."); } } Showable.java
package org.r4r.client; public interface Showable { public abstract void show(); } BeforeOne.java
package org.r4r.client; import org.r4r.framework.BeforeMethod; public class BeforeOne implements BeforeMethod { @Override public void doBefore() { System.out.println("Before advice is applied."); } } ProxyTest.java
package org.r4r.client; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class ProxyTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining proxy of one.."); Showable p=(Showable)f.getBean("proxy"); System.out.println("Proxy obtaining invoked."); p.show(); } } OutPut:Obtaining proxy of one.. Proxy obtaining invoked. Before advice is applied. Show() method of One invoked..
method, argument, method object and value returned by the Object are provided to the developer. Application developer may used the return value but can not change it. 37.5.Around Advice:-An around advice are used when some operations are to be performed before and after method call and controlled over the return value of the method is to be gain. To apply around advice implementation of "MethodInterceptor" interface need to be provided by the developer. This interface provide a method name invoke which received parameter of type of Invocation. MethodInvocation Object encapsulate invocation of the actual method of the target object and exposes the method name proceed() which is used by application developer to get the actual method invoked. 38.6.After Throws Advice:-An after throws advice is used to performed some operation between throwing and catching an exception. To implements after throws advice implementation of "ThrowsAdvice" interface need to be provided. It is the marker interface. The class which implements this interface can define a method name afterThrowing() which can have either of the following signature. public void afterThrowing(Exception e); public void afterThrowing(Methid m, Object[] arg, Object target);
<?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="t" class="org.r4r.One"/> <bean id="a1" class="org.r4r.BeforeAdvisor"/> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="t"/> <property name="interceptorNames"> <list><value>a1</value></list> </property> </bean> </beans> Showable.java
package org.r4r; public interface Showable { public abstract void show(); } BeforeAdvisor.java
package org.r4r; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeAdvisor implements MethodBeforeAdvice { @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("Before advice is applied.."); } } One.java
package org.r4r; public class One implements Showable { @Override public void show() { System.out.println("Show() method of One invoked.."); } } ProxyTest.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class ProxyTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining proxy of one.."); Showable p=(Showable)f.getBean("proxy"); System.out.println("Proxy obtaining invoked."); p.show(); } } OutPut:Obtaining proxy of one.. Proxy obtaining invoked. Before advice is applied.. Show() method of One invoked..
<bean id="t" class="org.r4r.One"/> <bean id="a1" class="org.r4r.BeforeAdvisor"/> <bean id="a2" class="org.r4r.AfterAdvisor"/> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="t"/> <property name="interceptorNames"> <list><value>a1</value> <value>a2</value></list> </property> </bean> </beans> Showable.java
package org.r4r; public interface Showable { public abstract void show(); } One.java
package org.r4r; public class One implements Showable { @Override public void show() { System.out.println("Show() method of One invoked.."); } } BeforeAdvisor.java
package org.r4r; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeAdvisor implements MethodBeforeAdvice { @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("Before advice is applied..");
} } AfterAdvisor.java
package org.r4r; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class AfterAdvisor implements AfterReturningAdvice { @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("After advisor is provide service.."); } } ProxyTest.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class ProxyTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining proxy of one.."); Showable p=(Showable)f.getBean("proxy"); System.out.println("Proxy obtaining invoked."); p.show(); } } OutPut:Obtaining proxy of one.. Proxy obtaining invoked. Before advice is applied.. Show() method of One invoked.. After advisor is provide service..
<?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="t" class="org.r4r.One"/> <bean id="a1" class="org.r4r.AroundAdviser" /> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="t"/> <property name="interceptorNames"> <list><value>a1</value> </list> </property> </bean> </beans> Showable.java
package org.r4r; public interface Showable { public abstract void show(); } One.java
package org.r4r; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class AroundAdviser implements MethodInterceptor { @Override public Object invoke(MethodInvocation mi) throws Throwable { System.out.println("Before advice is applied..."); Object temp=mi.proceed(); System.out.println("After advice is applied, "+temp+"\tis return by the method."); System.out.println("Returning failure from the advice"); return "failure"; } } ProxyTest.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class ProxyTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining proxy of one.."); Showable p=(Showable)f.getBean("proxy"); System.out.println("Proxy obtaining invoked."); p.show(); } }
OutPut:Obtaining proxy of one.. Proxy obtaining invoked. Before advice is applied... Show() method of One invoked.. After advice is applied, null is return by the method. Returning failure from the advice
<?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="t" class="org.r4r.One"/> <bean id="a2" class="org.r4r.ThrowAdvisor" /> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="t"/> <property name="interceptorNames"> <list> <value>a2</value> </list> </property> </bean> </beans> Showable.java
package org.r4r; public class One implements Showable { @Override public String show(int x){ if(x>0){ System.out.println("Show() of one invoked returning success"); return "success"; } else{ System.out.println("Shows() of one invoked, throwing exception"); throw(new IllegalArgumentException("It is thrown by show()")); } } } ThrowAdvisor.java
package org.r4r; import java.lang.reflect.Method; import org.springframework.aop.ThrowsAdvice; public class ThrowAdvisor implements ThrowsAdvice { /*public void afterThrowing(Exception e){ System.out.println("In throws advice because of following exception"+e); }*/ public void afterThrowing(Method m,Object args[],Object target,Exception e){ System.out.println("In throws advice because"+m.getName()+ "() throw following exception "+e.getMessage()+ " When invoked on the object of "+target.getClass().getName()+" Class."); } } AroundAdviser.java
import org.aopalliance.intercept.MethodInvocation; public class AroundAdviser implements MethodInterceptor { @Override public Object invoke(MethodInvocation mi) throws Throwable { System.out.println("Before advice is applied..."); Object temp=mi.proceed(); System.out.println("After advice is applied, "+temp+"\tis return by the method."); System.out.println("Returning failure from the advice"); return "failure"; } } ProxyTest.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class ProxyTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); System.out.println("Obtaining proxy of one.."); Showable p=(Showable)f.getBean("proxy"); try{ System.out.println("proxy obtained invoking show() with positive String s=p.show(5); System.out.println(s+" Is received by the client"); System.out.println("Invoking show() with negative value"); p.show(-2); }catch(Exception e){ System.out.println("Following exception caught in main"+e); } } } OutPut:Obtaining proxy of one.. proxy obtained invoking show() with positive value Show() of one invoked returning success success Is received by the client Invoking show() with negative value Shows() of one invoked, throwing exception In throws advice becauseshow() throw following exception It is thrown by show() When invoked
value");
on the object of org.r4r.One Class. Following exception caught in mainjava.lang.IllegalArgumentException: It is thrown by show()
42.Pointcut in Spring
42.1.Introduction:-By simply specify advices with bean in the configuration all the method of the bean are advice some time final control is required over the application of advices i.e an application developer may want applied some advices only to the selected method to the bean. Final control over the application of advices is provided by pointcuts. A pointcut is used by the IOC container to find out wither an advice can be applied or not. Framework provide different implementation of pointcut most commonly used implementation of which. 42.2.NameMatchMethodPointcut:-This pointcut implementation uses method name as criteria of finding out the applicability of advices. The pointcut simply specify a which method of a bean can be advice is does not specified the advices. Advices are associated to pointcut with the help of aspect implementation of aspect is called advisor in Spring AOP implementation framework provide predefine advisor. Most commonly used one these are before pointcut advisor. Following application demonstrate an user of pointcut or advisor to apply advises of selective method of bean. 42.3.NameMatchMethodPointcutAdvice:-One of the disadvantage of using pointcuts is entry of configuration information solution of this problem is provided by PointcutAdvisor class. A PointcutAdvisor class combined the functionality of a pointcut and advisor in to a
single unit.
The NameMatchMethodPointcutAdvisor class combined the functionality of NameMatchMethodPointcut and DefaultPointcutAdvisor using this class the configuration information is reduced as follows.
43.Example of NameMatchMethodPointcut
43.1.Introduction:-This pointcut implementation uses method name as criteria of finding out the applicability of advices. The pointcut simply specify a which method of a bean can be advice is does not specified the advices. Advices are associated to pointcut with the help of aspect implementation of aspect is called advisor in Spring AOP implementation framework provide predefine advisor. Most commonly used one these are before pointcut advisor. 41.2 .Technology use to run this source code:1.Spring2.5 jar file 2.Eclips Id 3.Tomcat Server 41.3 .Source 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="t" class="org.r4r.One"/> <bean id="a1" class="org.r4r.BeforeAdvisor"/> <bean id="a2" class="org.r4r.AfterAdvisor"/> <bean id="pc1" class="org.springframework.aop.support.NameMatchMethodPointcut"> <property name="mappedName" value="a"/> </bean> <bean id="pc2" class="org.springframework.aop.support.NameMatchMethodPointcut"> <property name="mappedName" value="b"/> </bean> <bean id="ad1" class="org.springframework.aop.support.DefaultPointcutAdvisor"> <property name="advice" ref="a1"/> <property name="pointcut" ref="pc1"/> </bean> <bean id="ad2" class="org.springframework.aop.support.DefaultPointcutAdvisor"> <property name="advice" ref="a2"/> <property name="pointcut" ref="pc2"/> </bean> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="t"/> <property name="interceptorNames"> <list> <value>ad1</value> <value>ad2</value></list> </property> </bean> </beans> AB.java
package org.r4r; public interface AB { public void a(); public void b(); } One.java
package org.r4r; public class One implements AB { @Override public void a() {
System.out.println("a() of one invoked"); } @Override public void b() { System.out.println("b() of one invoked"); } } AfterAdvisor.java
package org.r4r; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class AfterAdvisor implements AfterReturningAdvice { @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("After advisor is provide service.."); } } BeforeAdvisor.java
package org.r4r; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeAdvisor implements MethodBeforeAdvice { @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("Before advice is applied.."); } } ProxyTest.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class ProxyTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); AB proxy=(AB)f.getBean("proxy"); System.out.println("Proxy obtained invoking a()."); proxy.a(); System.out.println("Proxy obtained invoking b()"); proxy.b(); } } OutPut:Proxy obtained invoking a(). Before advice is applied.. a() of one invoked Proxy obtained invoking b() b() of one invoked After advisor is provide service..
44.Example of NameMatchMethodPointcutAdvice
44.1.Introduction:-One of the disadvantage of using pointcuts is entry of configuration information solution of this problem is provided by PointcutAdvisor class. A PointcutAdvisor class combined the functionality of a pointcut and advisor in to a single unit. The NameMatchMethodPointcutAdvisor class combined the functionality of NameMatchMethodPointcut and DefaultPointcutAdvisor using this class the configuration information is reduced as follows. 41.2 .Technology use to run this source code:1.Spring2.5 jar file 2.Eclips Id 3.Tomcat Server 41.3 .Source 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="t" class="org.r4r.One"/> <bean id="a1" class="org.r4r.BeforeAdvisor"/> <bean id="a2" class="org.r4r.AfterAdvisor"/> <bean id="pca1" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor"> <property name="advice" ref="a1"/> <property name="mappedName" value="a"/> </bean> <bean id="pca2" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor"> <property name="advice" ref="a2"/> <property name="mappedName" value="b"/> </bean> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="t"/> <property name="interceptorNames"> <list> <value>pca1</value> <value>pca2</value></list> </property> </bean> </beans>
AB.java
package org.r4r; public interface AB { public void a(); public void b(); } One.java
package org.r4r; public class One implements AB { @Override public void a() {
System.out.println("a() of one invoked"); } @Override public void b() { System.out.println("b() of one invoked"); } } BeforeAdvisor.java
package org.r4r; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeAdvisor implements MethodBeforeAdvice { @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("Before advice is applied.."); } } AfterAdvisor.java
package org.r4r; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class AfterAdvisor implements AfterReturningAdvice { @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("After advisor is provide service.."); } } ProxyTest.java
package org.r4r; import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;
public class ProxyTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory f=new XmlBeanFactory(r); AB proxy=(AB)f.getBean("proxy"); System.out.println("Proxy obtained invoking a()."); proxy.a(); System.out.println("Proxy obtained invoking b()"); proxy.b(); }NameMatchMethodPointcut.shtml } OutPut:Proxy obtained invoking a(). Before advice is applied.. a() of one invoked Proxy obtained invoking b() b() of one invoked After advisor is provide service..
1.Connection can be created using DriverManager, It can be obtained from a pool or can be obtained from a directory server. 2.Statement can be created in multiple ways using Statement, PreparedStatement and CallableStatement interface. 3.Usualy method which involves the predefine sequence of steps out of which some step can be varies are implemented in such a way that common steps are repeated in multiple implementation. 4.Template design pattern tries to be remove this problem to facilities definition of common steps only one in a template method and by allowing individual develop to provide the own implementation to the variable steps following example demonstrate the concept of template design pattern.
//This is a template method that facilitate of two number can be read from the keyboard from a file or from the network. Result can be displayed on the console, can be saved to a file or can be sent over the network i.e out of these steps two are variable.
abstract class Adder { public void add()//template method that uses method steps to define the sequence { int numArray[]=getNumber(); int result=numArray[0]+numArray[1]; manageResult(result); } public abstract int[] getNumber();//stub method representing. public void manageResult(int r);//variable step. }
46.Without using template insert, update, delete and select data Example
46.1.Introduction:-This example provide the difference between template design pattern and simple design pattern to insert , update, delete and select all data from the data base.
46.2 .Technology use to run this source code:1.Spring2.5 jar file 2.Eclips Id 3.Tomcat Server 46.3 .Source Code:ConnectionProvider.java
package org.r4r; import java.sql.Connection; import java.sql.DriverManager; public class ConnectionProvider { public static Connection getConnection() { Connection con=null; try{ Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost/tableone","root","root"); }catch(Exception e) { System.out.println(e); } return con; } } Emp.java
package org.r4r; public class Emp { int id; String name,job; int salary; public Emp() { super(); // TODO Auto-generated constructor stub } public Emp(int id, String name, String job, int salary) { super(); this.id = id; 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; } } EmpDao.java
package org.r4r; import java.sql.*; import java.util.Scanner; public class EmpDao { public void save(Emp emp){ try{ Connection con=ConnectionProvider.getConnection(); PreparedStatement stmt=con.prepareStatement("insert into emp values(?,?,?,?)"); stmt.setInt(1, emp.getId()); stmt.setString(2, emp.getName()); stmt.setString(3, emp.getJob()); stmt.setInt(4, emp.getSalary()); stmt.executeUpdate(); con.close(); }catch(Exception e){ System.out.println(e); } } public void update(Emp emp){ try{ Connection con=ConnectionProvider.getConnection();
Scanner in=new Scanner(System.in); System.out.println("Enter the id:"); int id=in.nextInt(); in.nextLine(); System.out.println("Enter the name:"); String name=in.nextLine(); System.out.println("Enter the job:"); String job=in.nextLine(); System.out.println("Enter the salary:"); int salary=in.nextInt(); in.nextLine(); PreparedStatement stmt=con.prepareStatement ("update emp set name=?, job=?, salary=? where id=?"); stmt.setInt(4, id); stmt.setString(1, name); stmt.setString(2, job); stmt.setInt(3, salary); stmt.executeUpdate(); con.close(); }catch(Exception e){ System.out.println(e); } } public void delete(Emp emp){ try{ Connection con=ConnectionProvider.getConnection(); Scanner in=new Scanner(System.in); System.out.println("Enter the id:"); int id=in.nextInt(); PreparedStatement stmt=con.prepareStatement("delete from emp where id=?"); stmt.setInt(1, id); stmt.executeUpdate(); con.close(); }catch(Exception e){ System.out.println(e); } } } InsertTest.java
package org.r4r; import java.util.Scanner; public class InsertTest { public static void main(String[] args) { Scanner in=new Scanner(System.in); EmpDao dao=new EmpDao(); while(true){ System.out.println("Enter the id:");
int id=in.nextInt(); in.nextLine(); System.out.println("Enter the name:"); String name=in.nextLine(); System.out.println("Enter the job:"); String job=in.nextLine(); System.out.println("Enter the salary:"); int salary=in.nextInt(); in.nextLine(); Emp emp=new Emp(id,name,job,salary); dao.save(emp); System.out.println("Insert continue write yes/no:"); String reg=in.nextLine(); if(reg.equals("no")) break; } System.out.println("You are successfully insert data..."); } } UpdateTest.java
package org.r4r; public class UpdateTest { public static void main(String[] args) { System.out.println("Update Emp Object....."); EmpDao dao=new EmpDao(); Emp emp=new Emp(); dao.update(emp); System.out.println("You are successfully update"); } } DeleteTest.java
package org.r4r; public class DeleteTest { public static void main(String[] args) { System.out.println("Deleted Emp Object....."); EmpDao dao=new EmpDao(); Emp emp=new Emp(); dao.delete(emp); System.out.println("You are successfully delete"); } }
OutPut:InsertTest Enter the id: 1005 Enter the name: Mukund Singh Enter the job: Java Developer Enter the salary: 25000 Insert continue write yes/no: no You are successfully insert data... UpdateTest Update Emp Object..... Enter the id: 1005 Enter the name: Bal Mukund Enter the job: Spring Develo Enter the salary: 30000 You are successfully update DeleteTest Deleted Emp Object..... Enter the id: 1005 You are successfully delete
<?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="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost/tableone"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <bean id="temp" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="ds"/> </bean> <bean id="dao" class="org.r4r.EmpTemplateDao"> <property name="template" ref="temp"/> </bean> </beans> Emp.java
package org.r4r; public class Emp { int id; String name,job; int salary; public Emp() { super(); } public Emp(int id, String name, String job, int salary) { super(); this.id = id; 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; } } EmpTemplateDao.java
package org.r4r; import import import import import import java.sql.Connection; java.sql.PreparedStatement; java.sql.ResultSet; java.sql.SQLException; java.util.List; java.util.Scanner;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; public class EmpTemplateDao { JdbcTemplate template; public JdbcTemplate getTemplate() { return template; } public void setTemplate(JdbcTemplate template) { this.template = template; } @SuppressWarnings("unchecked") public List getAllEmp(){ RowMapper mapper=new RowMapper() { @Override public Object mapRow(ResultSet rset, int index) throws SQLException Emp e=new Emp(); e.setId(rset.getInt(1)); e.setName(rset.getString(2)); e.setJob(rset.getString(3)); e.setSalary(rset.getInt(4)); return e; }; }
return template.query("select * from emp", mapper); } public void save(final Emp e){ PreparedStatementCreator psc=new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement stmt=null; try{ stmt=con.prepareStatement("insert into Emp stmt.setInt(1, e.getId()); stmt.setString(2, e.getName()); stmt.setString(3,e.getJob()); stmt.setInt(4, e.getSalary()); }catch(Exception ex){ System.out.println(ex); } } return stmt;
values(?,?,?,?)");
}; template.update(psc); } public void update(final Emp e){ PreparedStatementCreator psc=new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement stmt=null; try{ Scanner in=new Scanner(System.in); System.out.println("Enter the id: "); int id=in.nextInt(); stmt=con.prepareStatement ("update emp set name=?,job=?,salary=? where id=?"); stmt.setInt(4, id); stmt.setString(1, e.getName()); stmt.setString(2, e.getJob()); stmt.setInt(3, e.getSalary()); }catch(Exception ex){ System.out.println(ex); } return stmt; } }; template.update(psc); } public void delete(final Emp e){ PreparedStatementCreator psc=new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement stmt=null;
try{
where id=?");
Scanner in=new Scanner(System.in); System.out.println("Enter the id: "); int id=in.nextInt(); stmt=con.prepareStatement("delete from emp stmt.setInt(1, id);
} }
InsertTest.java
package org.r4r; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class InsertTest { public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("Obtaining dao from IOC container"); EmpTemplateDao dao=(EmpTemplateDao)ctx.getBean("dao"); System.out.println("Dao saved the Emp Object"); Emp e1=new Emp(101,"Amit","Engineer",25000); Emp e2=new Emp(102,"ArshRaj","Developer",25000); Emp e3=new Emp(103,"Dipu","Business Man",25000); Emp e4=new Emp(104,"Amar","Marketing Manager",25000); dao.save(e1);dao.save(e2);dao.save(e3);dao.save(e4); System.out.println("Emp object Save"); } } UpdateTest.java
public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("Obtaining dao from IOC container"); EmpTemplateDao dao=(EmpTemplateDao)ctx.getBean("dao"); System.out.println("Dao update the Emp Object"); Emp e=new Emp(222,"Mukund Singh","Software Engineer",55000); dao.update(e); System.out.println("Emp object Update"); } } DeleteTest.java
package org.r4r; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DeleteTest { public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("Obtaining dao from IOC container"); EmpTemplateDao dao=(EmpTemplateDao)ctx.getBean("dao"); System.out.println("Deleting Emp Object"); Emp e=new Emp(); dao.delete(e); System.out.println("Emp object delete"); } } SelectTest.java
package org.r4r; import java.util.*; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SelectTest { @SuppressWarnings("unchecked") public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("Obtaining dao from IOC container");
EmpTemplateDao dao=(EmpTemplateDao)ctx.getBean("dao"); System.out.println("Fetching Emp Objects"); List<Emp> list=dao.getAllEmp(); Iterator<Emp> itr=list.iterator(); System.out.println("Following objects are fetched."); while(itr.hasNext()){ Emp e=itr.next(); System.out.println(e.getId()+"\t"+e.getName()+"\t"+e.getJob() +"\t"+e.getSalary()); } } } OutPut:InsertTest Result Obtaining dao from IOC container Dao saved the Emp Object Emp object Save UpdateTest Result:Obtaining dao from IOC container Dao update the Emp Object Enter the id: 102 Emp object Update DeleteTest Result:Obtaining dao from IOC container Deleting Emp Object Enter the id: 102 Emp object delete SelectTest Result:Obtaining dao from IOC container Fetching Emp Objects Following objects are fetched. 103 Amar Marketing 101 ArshRaj Develo 25000 100 Amit Engi 25000
25000
Model:-Model component represent a data for spring MVC usually a map of model object is used as Model component. View:-View is a generic component of the framework which is responsible for presenting data to the end user. Multiple implementation of view are provided the framework to support different presentation technique. Controller:-Controller component provide the facility to change the state and flow the data. Controller component is responsible for the controlled the workflow of the web application in the spring framework. 48.3.How can implement spring MVC:Following steps are required to used spring MVC implementation:Step 1:-First select the web project in our IDE and add the capability of spring framework (it means that add the jar file). The following jar file are add before implement the spring MVC application 1.Spring 2.5 core Library 2.Spring 2.5 web Library Step 2:-Servlet entry is to be made in web.xml file for DispatcherServlet class
<?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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>login</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>*.spring</url-pattern> </servlet-mapping> </web-app> Step 3:-Define in xml file to specified a mapping requested url and controller of spring application. This file is conventionally name as follows Example:-ServletName-servlet.xml Step 4:-If DispatcherServlet is assign "frontController" name in web.xml then this file must be named as "frontController-servlet.xml" Step 5:-The file "frontController-servlet.xml" used the bean element to mapped request url and controller Class Example: <?xml version="1.0" encoding="UTF-8"?>
<beans
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost/tableone</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> </bean> <bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg> <ref local="datasource"/> </constructor-arg> </bean> <bean id="loginModel" class="org.r4r.LoginModel"/> Step 6:-Define controller class , Controller is a subclass of AbstractController class. AbstractController class provides an abstract method name handleRequestInternal(HttpServletRequest request,HttpServletResponse response);
which is invoked each time a request of the controller received. This method returned a ModelAndView object. 9.Example of Spring MVC Implementation
49.1.Introduction:-In Spring MVC implementation the controller is an application component. Which is responsible for processing the request. It does not controlled the workflow of request processing as done by struts controller. Workflow of request is controlled by front controller which is implemented by servlet name "DispatcherServlet" is provides a single entry point in to the application. 49.2 .Technology use to run this source code:1.Spring2.5 jar file 2.Eclips Id 3.Tomcat Server 49.3 .Source Code:-
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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>frontController</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>frontController</servlet-name> <url-pattern>*.bean</url-pattern> </servlet-mapping> </web-app>
frontController.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 name="/first.bean" class="org.r4r.SecondControlleer"></bean> </beans> MyView.java
package org.r4r; import java.io.PrintWriter; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.View;
public class MyView implements View { public String getContentType() { } return "text/html";
@SuppressWarnings("unchecked") public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter out=response.getWriter(); out.println("This view is generated by spring view...."); out.println("First Name:-\t"+model.get("firstName")); out.println("Last Name:-\t"+model.get("lastName")); out.close(); } } FirstController.java
package org.r4r; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class FirstController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, String> map=new HashMap<String, String>(); map.put("firstName", "Mukund"); map.put("lastName", "Singh"); ModelAndView mav=new ModelAndView(new MyView(),map); return mav; } } index.jsp
<?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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>frontController</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet>
frontController-servlet.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="viewResolver" class=" org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <bean name="/first.bean" class="org.r4r.FirstController"> <property name="message" value="My Name Is MUKUND"></property> </bean> </beans> SecondController.java
package org.r4r; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class FirstController extends AbstractController { private String message; @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub return new ModelAndView("welcomePage","welcomeMessage",message); } public String getMessage() { return message;
welcomePage.jsp
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome Page</title> </head> <body> ${welcomeMessage} </body> </html>
OutPut:-
51.1.Introduction:-The Struts 2.x is the web application framework in Java Technology, this framework provide the concept of Model View Controller (MVC) and Interceptor to develop the web application. The Spring framework provide the facility to integrate with other framework and Developed the application in java. This tutorial provide the facility how can integrate between 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.x
framework:-
Step 1:-First select the web project in our IDE and add the capability of spring 2.5 and Struts 2.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 configuration information. Step 4:-Also create applicationContext.xml in WEB-INF folder to give the spring configuration information. 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.
<?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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Struts2Example14</display-name> <filter>
<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
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
OutPut:-