0% found this document useful (0 votes)
5 views149 pages

FRAMEWORK

The document provides an overview of the Hibernate framework, detailing its purpose as an Object Relational Mapping (ORM) tool that simplifies database operations in Java applications. It covers the structure of a Hibernate application, including configuration, CRUD operations, and the use of XML and annotation approaches for mapping. Additionally, it discusses advantages of Hibernate, such as performance, caching, and ease of use in data persistence.

Uploaded by

Amit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views149 pages

FRAMEWORK

The document provides an overview of the Hibernate framework, detailing its purpose as an Object Relational Mapping (ORM) tool that simplifies database operations in Java applications. It covers the structure of a Hibernate application, including configuration, CRUD operations, and the use of XML and annotation approaches for mapping. Additionally, it discusses advantages of Hibernate, such as performance, caching, and ease of use in data persistence.

Uploaded by

Amit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 149

HIBERNATE FRAMEWORK

DAY-1
What is Framework?
 Fr is a soft arch that provides a structure, guidelines and
reusable component to facilitate the development of an
application.
 Fr handles the infrastructure so that you can focus on logic
 Control Flow will be managed by framework itself
 To simplify Development

 GET THE FRAMEWORK


 PUT THE DATA (id name add salary)
 PUT YOUR CONFIGURATION (url user pass driver)
 TELL WHAT TO DO
 GET THE RESULT

EXAMPLE:
 CREATE A TABLE
 SQL
 ResultSet
 Create Model Object
 Create a List
 Loop : Add Model into List
 return List

Hibernate:
 get the List (Table, SQL, Model Object, Model->Setter, List,
add(model),return List)
 return List

What is Hibernate?
 Hibernate is a framework which provides an ORM tool to
simplify the development (DAO)
 Hibernate ORM tool (Object Relational Mapping)
 To achieve Data Persistency
 GAVIN KING 2001
 Internally it uses JDBC API
 Third Party

ADVANTAGE:
 Fast Performance
 Pooling Mechanism
 SQL Independent (SQL,HQL,PURE JAVA)
 CACHING MECHANISM
 Auto Table Creation
 No Checked Exp
 PK Generation
 Easily Pagination
 Versioning
 EASY CRUD
 Simplify
 Job Opp

ORM tool (Object Relational Mapping Tool)


 It is a programming technique that simplify interaction
between Object and RDBMS

DAY-2
In Hibernate we can Perform DB operation in two ways
1.SINGLE OPERATION
2.BULK OPERATION

SINGLE OPERATION (Work with PK)


To insert Data we should establish the Connection
1.XML Approach
2.Annotation Approach

NOTE:

XML Approach:
HBN is a third party framework so we need its
JARs
Version: HBN5.X

XML: Language Agnostic


 It needs DOCTYPE DEFINITION (Xml Purpose, Validate, Error
check)
 More line of code
 More files
 Configuration and Mapping decoupled (SEPERATION CONCERN)
 DYNAMIC UPDATE
 Legacy application
CONVENTION OVER CONFIGURATION

package com.mainapp;
import java.io.Serializable;
import java.util.Scanner;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Launch {

public static void main(String[] args) {

//LOADS CFG FILE


Configuration configuration = new Configuration();
configuration.configure();

//SETUP READY
SessionFactory sessionFactory =
configuration.buildSessionFactory();

//Now U can Peform CRUD (Inbuilt Connection)


Session session = sessionFactory.openSession();

//Transaction
Transaction trs = session.beginTransaction();

//DATA INSERT

Scanner scanner = new Scanner(System.in);


System.out.println("ENTER EID");
int eid=scanner.nextInt();
System.out.println("ENTER ENAME");
String ename=scanner.next();
System.out.println("ENTER EADDRESS");
String eaddress=scanner.next();
System.out.println("ENTER ESALARY");
int esalary=scanner.nextInt();

Employee employee = new Employee(eid, ename, eaddress, esalary);


int pk = (int) session.save(employee);
trs.commit();

System.out.println(pk);

session.close();
//connection back to pool
//cache memory free

}
}

package com.mainapp;
//Entity Class
public class Employee {

private int eid;


private String ename;
private String eaddress;
private int esalary;

public Employee(int eid, String ename, String eaddress, int esalary) {


super();
this.eid = eid;
this.ename = ename;
this.eaddress = eaddress;
this.esalary = esalary;
}

public int getEid() {


return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getEaddress() {
return eaddress;
}
public void setEaddress(String eaddress) {
this.eaddress = eaddress;
}
public int getEsalary() {
return esalary;
}
public void setEsalary(int esalary) {
this.esalary = esalary;
}
@Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ",
eaddress=" + eaddress + ", esalary=" + esalary + "]";
}
}

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


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

<hibernate-mapping>

<class name="com.mainapp.Employee" table="employee">


<id name="eid" column="id" ></id>
<property name="ename" column="name"></property>
<property name="eaddress" column="address"></property>
<property name="esalary" column="salary"></property>
</class>

</hibernate-mapping>

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


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

<hibernate-configuration>
<session-factory>
<property
name="connection.driver_Class">com.mysql.cj.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3309/test</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>

DAY-3
Single Operation
 Read Based on PK
 Hibernate will use Zero Parameterized
Constructor to create object of your Entity class
then it will call setter to set all values and you
will get object
package com.mainapp;
import java.util.Scanner;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Launch {

public static void main(String[] args) {

SessionFactory sf = getConnection();
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("P1->Insert\nP2->Read\nP3->Update\nP4-
>Delete\nP5->InsertORUpdate\nP6->EXIT");
System.out.print("Enter Choice:");
int chocie = scanner.nextInt();//15 \n
scanner.nextLine();
if(chocie==6)
{
System.out.println("THANKS FOR USING");
break;
}
switch (chocie) {
case 1:
insert(sf);
break;
case 2:
read(sf);
break;
case 3:
update(sf);
break;
case 4:
delete(sf);
break;
case 5:
insertOrUpdate(sf);
break;
default:
break;
} //end of switch
}//end of while
}

private static void insertOrUpdate(SessionFactory sf) {

Session session = sf.openSession();


//Transaction
Transaction trs = session.beginTransaction();
//DATA INSERT
Scanner scanner = new Scanner(System.in);
System.out.println("ENTER EID"); //11
int eid=scanner.nextInt();
System.out.println("ENTER ENAME");
String ename=scanner.next();
System.out.println("ENTER EADDRESS");
String eaddress=scanner.next();
System.out.println("ENTER ESALARY");
int esalary=scanner.nextInt();

Employee employee = new Employee(eid, ename, eaddress, esalary);


session.saveOrUpdate(employee);
trs.commit();
}

private static void delete(SessionFactory sf) {

Session session = sf.openSession();

Scanner scanner = new Scanner(System.in);


System.out.println("ENTER EID");
int eid=scanner.nextInt();

Employee employee = session.get(Employee.class, eid);


if(employee!=null) {

Transaction trs = session.beginTransaction();


session.delete(employee);
trs.commit();
System.out.println("DATA DELETED");
}
}

private static void update(SessionFactory sf) {

Session session = sf.openSession();

Scanner scanner = new Scanner(System.in);


System.out.println("ENTER EID");
int eid=scanner.nextInt();//15

System.out.println("ENTER NEW SALARY");


int newsalary=scanner.nextInt();

Employee employee = session.get(Employee.class, eid);


if(employee!=null) {

employee.setEsalary(newsalary);
Transaction trs = session.beginTransaction();
session.update(employee);
trs.commit();
System.out.println("UPDATED");

}else {
System.out.println("NOT EXIST");
}
}

private static void read (SessionFactory sf) {

Session session = sf.openSession();

Scanner scanner = new Scanner(System.in);


System.out.println("ENTER EID");
int eid=scanner.nextInt();

Employee employee = session.get(Employee.class, eid);


if(employee!=null)
System.out.println(employee);
else
System.out.println("NOT EXIST");

//FIRST LEVEL CACHE


// employee = session.get(Employee.class, eid);
// System.out.println(employee);

session.close();
}

private static void insert(SessionFactory sf) {

Session session = sf.openSession();


//Transaction
Transaction trs = session.beginTransaction();
//DATA INSERT
Scanner scanner = new Scanner(System.in);
System.out.println("ENTER EID");
int eid=scanner.nextInt();
System.out.println("ENTER ENAME");
String ename=scanner.next();
System.out.println("ENTER EADDRESS");
String eaddress=scanner.next();
System.out.println("ENTER ESALARY");
int esalary=scanner.nextInt();

Employee employee = new Employee(eid, ename, eaddress, esalary);


int pk = (int) session.save(employee);
trs.commit();

System.out.println(pk);

session.close();
//connection back to pool
//cache memory free
}

private static SessionFactory getConnection() {


//LOADS CFG FILE
Configuration configuration = new Configuration();
configuration.configure();

//SETUP READY
SessionFactory sessionFactory =
configuration.buildSessionFactory();

return sessionFactory;

}
}

CRUD PURE JAVA: Mapping and


Configuration
package com.mainapp;
import java.util.Properties;
import java.util.Scanner;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
public class Launch {

public static void main(String[] args) {

SessionFactory sf = getConnection();
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("P1->Insert\nP2->Read\nP3->Update\nP4-
>Delete\nP5->InsertORUpdate\nP6->EXIT");
System.out.print("Enter Choice:");
int chocie = scanner.nextInt();//15 \n
scanner.nextLine();
if(chocie==6)
{
System.out.println("THANKS FOR USING");
break;
}
switch (chocie) {
case 1:
insert(sf);
break;
case 2:
read(sf);
break;
case 3:
update(sf);
break;
case 4:
delete(sf);
break;
case 5:
insertOrUpdate(sf);
break;
default:
break;
} //end of switch
}//end of while
}

private static void insertOrUpdate(SessionFactory sf) {

Session session = sf.openSession();


//Transaction
Transaction trs = session.beginTransaction();
//DATA INSERT
Scanner scanner = new Scanner(System.in);
System.out.println("ENTER EID"); //11
int eid=scanner.nextInt();
System.out.println("ENTER ENAME");
String ename=scanner.next();
System.out.println("ENTER EADDRESS");
String eaddress=scanner.next();
System.out.println("ENTER ESALARY");
int esalary=scanner.nextInt();

Employee employee = new Employee(eid, ename, eaddress, esalary);


session.saveOrUpdate(employee);
trs.commit();
}

private static void delete(SessionFactory sf) {

Session session = sf.openSession();

Scanner scanner = new Scanner(System.in);


System.out.println("ENTER EID");
int eid=scanner.nextInt();

Employee employee = session.get(Employee.class, eid);


if(employee!=null) {

Transaction trs = session.beginTransaction();


session.delete(employee);
trs.commit();
System.out.println("DATA DELETED");
}
}

private static void update(SessionFactory sf) {

Session session = sf.openSession();


Scanner scanner = new Scanner(System.in);
System.out.println("ENTER EID");
int eid=scanner.nextInt();//15

System.out.println("ENTER NEW SALARY");


int newsalary=scanner.nextInt();

Employee employee = session.get(Employee.class, eid);


if(employee!=null) {

employee.setEsalary(newsalary);
Transaction trs = session.beginTransaction();
session.update(employee);
trs.commit();
System.out.println("UPDATED");

}else {
System.out.println("NOT EXIST");
}
}

private static void read (SessionFactory sf) {

Session session = sf.openSession();

Scanner scanner = new Scanner(System.in);


System.out.println("ENTER EID");
int eid=scanner.nextInt();

Employee employee = session.get(Employee.class, eid);


if(employee!=null)
System.out.println(employee);
else
System.out.println("NOT EXIST");

//FIRST LEVEL CACHE


// employee = session.get(Employee.class, eid);
// System.out.println(employee);

session.close();
}

private static void insert(SessionFactory sf) {

Session session = sf.openSession();


//Transaction
Transaction trs = session.beginTransaction();
//DATA INSERT
Scanner scanner = new Scanner(System.in);
System.out.println("ENTER EID");
int eid=scanner.nextInt();
System.out.println("ENTER ENAME");
String ename=scanner.next();
System.out.println("ENTER EADDRESS");
String eaddress=scanner.next();
System.out.println("ENTER ESALARY");
int esalary=scanner.nextInt();

Employee employee = new Employee(eid, ename, eaddress, esalary);


int pk = (int) session.save(employee);
trs.commit();

System.out.println(pk);

session.close();
//connection back to pool
//cache memory free
}

private static SessionFactory getConnection() {


//LOADS CFG FILE
Configuration configuration = new Configuration();

Properties properties = new Properties();


properties.put(Environment.URL,
"jdbc:mysql://localhost:3309/test");
properties.put(Environment.USER, "root");
properties.put(Environment.PASS, "");
properties.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
properties.put(Environment.HBM2DDL_AUTO, "update");
properties.put(Environment.SHOW_SQL, true);
properties.put(Environment.FORMAT_SQL, true);

configuration.setProperties(properties);
configuration.addAnnotatedClass(Employee.class);

//SETUP READY
SessionFactory sessionFactory =
configuration.buildSessionFactory();
return sessionFactory;
}
}

package com.mainapp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//Entity Class
@Entity
@Table(name="myemployee")
public class Employee {

@Id
@Column(name = "id")
private int eid;

@Column(name = "name" , length = 30 )


private String ename;

@Column(name = "address" , length = 500)


private String eaddress;

@Column(name = "salary")
private int esalary;

public Employee() {
}

public Employee(int eid, String ename, String eaddress, int esalary) {


super();
this.eid = eid;
this.ename = ename;
this.eaddress = eaddress;
this.esalary = esalary;
}

public int getEid() {


return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getEaddress() {
return eaddress;
}
public void setEaddress(String eaddress) {
this.eaddress = eaddress;
}
public int getEsalary() {
return esalary;
}
public void setEsalary(int esalary) {
this.esalary = esalary;
}
@Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ",
eaddress=" + eaddress + ", esalary=" + esalary + "]";
}
}
DAY-4
Complex Data
Employee
 private int eid
 private String ename;
 private String eaddress;
 private int esalary;
 private Account eaccount;
 private Education eeducation;
Account
 private int accNo;
 private String bankName;
 private int amount;
Education
private int rollNo;
private String clgName;
private int percentage;
TABLE: 10 COLUMNS
DAY-5
Versioning
USER DATA: INSERT
id fname lname age username password
version
11 raju pqrs 66 raju@pqrs 123456
0
USER DATA: UPDATE
id fname lname age username password
version
11 raju pqrs 66 raju@ops 123456
3

getVersion->3
if (version>2)
Don’t Update
else
Update
 BULK OPERATION:
 NATIVE SQL APPROACH
 PAGINATION
 HQL
 CRITERIA

DAY-6
BULK OPERATION (READ UPDATE DELETE)
1.SQL
2.HQL
3.PURE JAVA

SQL Approach OR NativeSQL approach


@NamedNativeQuery : we can separate
out SQL query from the business logic (We
can reuse our query)
without add Entity:
 List<Object[]>
eid ename eaddress esalary
1
2
Row1: Object[obj1,obj2,obj3,obj4]
Row2: Object[obj1,obj2,obj3,obj4]
List<Object[]>

DAY-7
Pagination
20 Entries
 SetFirstResult=0
 Max result = 4
ROW: 1 2 3 4
 SetFirstResult=4
 Max result = 4
ROW: 5 6 7 8

DAY-8
HQL(Hibernate Query Language)
->To perform bulk operation (READ DELETE
UPDATE)
->We cannot perform insert operation in HQL
->you can copy data from one table to another
HQL is database independent
SQL
 From table name
 select * from emPloyEe;(Valid)
HQL
 From Entity Name
 from Employee; (Valid)
 from employee; (Invalid)

 insert into tb(colms…) values(….) (INVALID)


 into into tb1(colms…) select from tb2
(VALID)
DAY-9
HQL Polymorphic query
Subtopic: Hibernate Inheritance
@Inheritance(strategy = InheritanceType.JOINED)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Inheritance(strategy =
InheritanceType.TABLE_PER_CLASS)

DAY-10
HQL Supports Polymorphic query ( from
Parent class -> Child classes access )
private static void readHQL(SessionFactory sf) {

Session session = sf.openSession();


String hql="from Player";

Query query = session.createQuery(hql);


List<Player> list = query.list();

for(Player p : list) {

if(p instanceof Cricketer) {

Cricketer c=(Cricketer) p;
System.out.println(c);
}
else {
Footballer f=(Footballer) p;
System.out.println(f);
}
}

private static void readSQL(SessionFactory sf) {

Session session = sf.openSession();

String sql="select p.pid, p.pname, c.crun, c.ctype


from player p join cricketer c on p.pid=c.pid "
+ "UNION ALL "
+"select p.pid, p.pname, f.fgoal, f.ftype from
player p join footballer f on p.pid=f.pid";

NativeQuery nativeQuery =
session.createNativeQuery(sql);
List<Object[]> list = nativeQuery.getResultList();

for(Object[] orr : list) {

for(Object obj: orr) {


System.out.print(obj+" ");
}
System.out.println();
}
}

DAY-11
Hibernate Mapping : it defines how java objects
map to the Relational database tables
Object [ Object ]Separate Table
 One to One Mapping
->Unidirectional ->Bidirectional
 One to Many Mapping
 Many to One Mapping
 Many to Many Mapping

package com.mainapp;
import java.util.Properties;
import java.util.Scanner;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
public class Launch {

public static void main(String[] args) {


SessionFactory sf = getConnection();
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("P1->Insert\nP2-
>ReadFromPlayer\nP3->ReadFromAdhaar\nP4->Delete\nP5-
>EXIT");
System.out.print("Enter Choice:");
int chocie = scanner.nextInt();
scanner.nextLine();
if (chocie == 5) {
System.out.println("THANKS FOR
USING");
break;
}
switch (chocie) {
case 1:
insert(sf);
break;
case 2:
readFromPlayer(sf);
break;

case 3:
readFromAhdaar(sf);
break;

default:
break;
}
}
}

private static void readFromAhdaar(SessionFactory


sf) {

Session session = sf.openSession();


Adhaar adhaar = session.get(Adhaar.class,
121212);
System.out.println(adhaar.getAdhaarNo());
System.out.println(adhaar.getAdhaarName());

System.out.println(adhaar.getPlayer().getPid());

System.out.println(adhaar.getPlayer().getPname());

private static void readFromPlayer(SessionFactory


sf) {
Session session = sf.openSession();
Player player = session.get(Player.class, 11);
System.out.println(player);
}

private static void insert(SessionFactory sf) {


Session session = sf.openSession();
Transaction t = session.beginTransaction();

Adhaar adhaar = new Adhaar(121212, "xyz oo");


Player p = new Player(11, "xyz",adhaar);
adhaar.setPlayer(p);

session.save(p);

t.commit();
}

private static SessionFactory getConnection() {


Configuration configuration = new
Configuration();
Properties properties = new Properties();
properties.put(Environment.URL,
"jdbc:mysql://localhost:3309/mapping");
properties.put(Environment.USER, "root");
properties.put(Environment.PASS, "");
properties.put(Environment.DRIVER,
"com.mysql.cj.jdbc.Driver");
properties.put(Environment.HBM2DDL_AUTO,
"create");
properties.put(Environment.SHOW_SQL, true);
properties.put(Environment.FORMAT_SQL, true);
configuration.setProperties(properties);
configuration.addAnnotatedClass(Player.class);
configuration.addAnnotatedClass(Adhaar.class);
SessionFactory sessionFactory =
configuration.buildSessionFactory();
return sessionFactory;
}
}

package com.mainapp;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "adhaar")
public class Adhaar {

@Id
@Column(name = "adhaarno")
private int adhaarNo;

@Column(name = "adhaarname")
private String adhaarName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "pid")
private Player player;

public Adhaar() {
// TODO Auto-generated constructor stub
}
public Adhaar(int adhaarNo, String adhaarName) {
super();
this.adhaarNo = adhaarNo;
this.adhaarName = adhaarName;
}

public Adhaar(int adhaarNo, String adhaarName,


Player player) {
super();
this.adhaarNo = adhaarNo;
this.adhaarName = adhaarName;
this.player = player;
}

public int getAdhaarNo() {


return adhaarNo;
}

public void setAdhaarNo(int adhaarNo) {


this.adhaarNo = adhaarNo;
}

public String getAdhaarName() {


return adhaarName;
}

public Player getPlayer() {


return player;
}

public void setPlayer(Player player) {


this.player = player;
}

public void setAdhaarName(String adhaarName) {


this.adhaarName = adhaarName;
}
// @Override
// public String toString() {
// return "Adhaar [adhaarNo=" + adhaarNo + ",
adhaarName=" + adhaarName + "]";
// }

// @Override
// public String toString() {
// return "Adhaar [adhaarNo=" + adhaarNo + ",
adhaarName=" + adhaarName + ", player=" + player + "]";
// }

package com.mainapp;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "player")
public class Player {

@Id
@Column(name = "pid")
private int pid;

@Column(name = "pname")
private String pname;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "adhaarno")
private Adhaar adhaar;

public Player() {
// TODO Auto-generated constructor stub
}

public Player(int pid, String pname, Adhaar adhaar)


{
super();
this.pid = pid;
this.pname = pname;
this.adhaar = adhaar;
}

public int getPid() {


return pid;
}

public void setPid(int pid) {


this.pid = pid;
}

public String getPname() {


return pname;
}

public void setPname(String pname) {


this.pname = pname;
}

public Adhaar getAdhaar() {


return adhaar;
}

public void setAdhaar(Adhaar adhaar) {


this.adhaar = adhaar;
}

@Override
public String toString() {
return "Player [pid=" + pid + ", pname=" +
pname + ", adhaar=" + adhaar + "]";
}
}

DAY-12
 ONE TO MANY
 MANY TO ONE
 MANY TO MANY (UNI/BI)
DAY-13
CRITERIA API
->It is a feature provided by JPA to construct dynamic and database
independent query to interact with databases
->this is pure Java approach
->You can perform BULK Operation (READ UPDATE DELETE)
->ClassName and field Names
package com.mainapp;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.hibernate.query.Query;
public class Launch {

public static void main(String[] args) {

SessionFactory sf = getConnection();
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("P1->Insert\nP2->Read\nP3-
>Update\nP4->Delete\nP5->Test");
System.out.print("Enter Choice:");
int chocie = scanner.nextInt();
scanner.nextLine();
if (chocie == 6) {
System.out.println("THANKS FOR USING");
break;
}
switch (chocie) {
case 1:
insert(sf);
break;
case 2:
read(sf);
break;

case 3:
update(sf);
break;

case 4:
delete(sf);
break;

case 5:
test(sf);
break;
default:
break;
}
}
}

private static void test(SessionFactory sf) {


Session session = sf.openSession();
Criteria criteria =
session.createCriteria(Player.class);

//pid,pname-> Projection

ProjectionList projectionList =
Projections.projectionList();
projectionList.add(Projections.property("pid"));
projectionList.add(Projections.property("pname"));

SimpleExpression lt = Restrictions.lt("pid",4);
criteria.setProjection(projectionList);
criteria.add(lt);

List<Object[]> list = criteria.list();


for(Object orr[] : list) {
for(Object o : orr) {
System.out.println(o);
}
}
}

private static void insert(SessionFactory sf) {


Session session = sf.openSession();

for(int i=1;i<=10;i++) {
Transaction t = session.beginTransaction();
Player player = new Player("raju"+i, "CSK"+i);
session.save(player);
t.commit();
}
}

private static void read(SessionFactory sf) {


Session session = sf.openSession();

//IT WILL PROVIDE YOU CRITERIA EX. READ UPDATE DELETE


CriteriaBuilder criteriaBuilder =
session.getCriteriaBuilder();
CriteriaQuery<Player> readCriteria =
criteriaBuilder.createQuery(Player.class); //READ OPERATION
Root<Player> root = readCriteria.from(Player.class);
//YOU CAN SELECT PID PNAME PADDRESS

//select id,name from criteriaplayer where id<6 and


name like '%2'

readCriteria.multiselect(root.get("pid"),root.get("pname"));
//select id,name from criteriaplayer

Predicate c1 =
criteriaBuilder.lessThan(root.get("pid"), 6); //id<6

Predicate c2 = criteriaBuilder.like(root.get("pname"),
"%2"); //name like '%2'

readCriteria.where(criteriaBuilder.and(c1,c2)); //where
id<6 and name like '%2'

Query<Player> query =
session.createQuery(readCriteria);
List<Player> list = query.list();
System.out.println(list);
}

private static void update(SessionFactory sf) {


Session session = sf.openSession();
Transaction t = session.beginTransaction();
//update criteriaplayer set name='kaju' where id<5

CriteriaBuilder criteriaBuilder =
session.getCriteriaBuilder();
CriteriaUpdate<Player> updateCriteria =
criteriaBuilder.createCriteriaUpdate(Player.class);
Root<Player> root = updateCriteria.from(Player.class);

updateCriteria.set(root.get("pname"), "kaju"); // set


name='kaju'
updateCriteria.where(criteriaBuilder.lessThan(
root.get("pid"), 5));
Query<Player> query =
session.createQuery(updateCriteria);
query.executeUpdate();
t.commit();

}
private static void delete(SessionFactory sf) {
Session session = sf.openSession();

Transaction t = session.beginTransaction();
//delete from criteriaplayer where id>6

CriteriaBuilder criteriaBuilder =
session.getCriteriaBuilder();
CriteriaDelete<Player> criteriaDelete =
criteriaBuilder.createCriteriaDelete(Player.class);
Root<Player> root = criteriaDelete.from(Player.class);
criteriaDelete.where(criteriaBuilder.greaterThan(
root.get("pid"), 6));

Query<Player> query =
session.createQuery(criteriaDelete);
query.executeUpdate();
t.commit();

private static SessionFactory getConnection() {


Configuration configuration = new Configuration();
Properties properties = new Properties();
properties.put(Environment.URL,
"jdbc:mysql://localhost:3309/mapping");
properties.put(Environment.USER, "root");
properties.put(Environment.PASS, "");
properties.put(Environment.DRIVER,
"com.mysql.cj.jdbc.Driver");
properties.put(Environment.HBM2DDL_AUTO, "update");
properties.put(Environment.SHOW_SQL, true);
//properties.put(Environment.FORMAT_SQL, true);
configuration.setProperties(properties);
configuration.addAnnotatedClass(Player.class);
SessionFactory sessionFactory =
configuration.buildSessionFactory();
return sessionFactory;
}
}
SPRING FRAMEWORK
DAY 1:
Why we should learn Spring Framework?
->To simply development
->We can develop application rapidly
->Spring works for every layer
->it reduces line of code
->easy to maintance
->Supports Robustness
->Best Suitable for enterprise application development
WEB APPLICATION Ex. Amazon
DESKTOP GUI APPLICATION Ex. PAINT
STANDALONE APPLICATION Ex. CONSOLE BASED APPLICATION
CLOUD APPLICATION Ex. AWS GDRIVE
DISTRIBUTED APPLICATION Ex. Amazon
EMBEDDED APPLICATION Ex. C/C++ embedded
application/shadi wala board
IOT APPLICATION Ex. HOIUSE HOLD SMART DEVICES

PRESENTATION LAYER->BUSINESS LAYER->DATA


STORAGE LAYER
View->Controller->Service->Dao->Storage
PYTHON----->JAVA(DATABASE) RESTAPI
MICROSERVICES (MULTIPLE SERVERS)
What is Framework?
->it is a software arch that provides a structure, guidelines and reusable
component to facilitate the development
->Less Control
->It uses libraries

What is Spring Framework?


Spring is an Open Source Framework
Spring is a java platform that provides complete infrastructure
to support Java development; spring handles the infrastructure
so that u can focus on main business logic
Spring is a lightweight framework
Spring supports pojo based programming

Spring Modules:
1. Spring Core
2. Spring JDBC
3. Spring MVC

SPRING FRAMEWORK
DAY 2:
Spring Core
->It is a module of spring framework
->it teaches how to manage objects
OBJECT MANAGEMENT
->Object Creation
->Object life cycle
->Object injection/Dependency Injection

Note: new keyword creates tight coupling


Launch----------------------------------------->Demo
( BEAN )
(main)

Spring IOC(Inversion of control) Container


->it is a core component of Spring Core
->it is used to manage objects often referred as bean
->it acts like a boss

Types of IOC container


1.BeanFactory (Deprecated) (Interface) 3.X
2.ApplicationContext(Latest) (Interface)
IOC: it is a design pattern (1990’s, Hollywood Principle: don’t call us, we
will call you)
SPRING FRAMEWORK
DAY 3:
BeanFactory IOC Container
Impl: XmlBeanFactory
1.Lazy Loading
2.Resource Object
3.Less Features

Spring Core Jars: (5.3.1)


 Spring core jar
 Spring beans jar
 Spring jcl jar
 Spring context jar
 Spring expression jar

Note: Interface 21(Old Name)


ApplicationContext IOC Container
Impl: ClassPathXmlApplicationContext
1.Eager Loading
2.More Features

SPRING FRAMEWORK
DAY 4:
Bean Scope:
 Singleton (bydeafult) : Object will be created only once and each
time when you ask for object it will share same object
 Prototype (Object will create when u invoke getBean() and every
time IOC container will provide a new Object)
package com.mainapp;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new
ClassPathXmlApplicationContext("bean.xml");
System.out.println("RAJU ACCOUNT CREATION");

Account acc1=(Account)ac.getBean("acc");
acc1.setUsername("RAJU123");
acc1.setPassword("123456");
acc1.setFullName("RAJU KK");
acc1.setAddress("MUMBAI");

System.out.println(acc1);

System.out.println("KAJU ACCOUNT CREATION");

Account acc2=(Account)ac.getBean("acc");
acc2.setUsername("KAJU123");
acc2.setPassword("223456");
acc2.setFullName("KAJU KK");
acc2.setAddress("HYDRABAD");

System.out.println(acc2);

System.out.println("****BOTH ACCOUNT DETAILS****");


System.out.println(acc1);
System.out.println(acc2);
}
}
package com.mainapp;

public class Account {

private String username;


private String password;
private String fullName;
private String address;

public Account() {
System.out.println("ACC INSTANTIATION");
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public String getFullName() {


return fullName;
}

public void setFullName(String fullName) {


this.fullName = fullName;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

@Override
public String toString() {
return "Account [username=" + username + ", password=" + password
+ ", fullName=" + fullName + ", address="
+ address + "]";
}
}

<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <!-- bean
definitions here -->

<bean id="acc" class="com.mainapp.Account" scope="prototype" > </bean>

</beans>
Dependency Injection through
XML
->Dependency injection term is used to refer injecting a dependent object of a
class into another class.
1.Setter Injection
2.Constructor Injection
Controller{
private Service service; //Dependency
public Controller(){
service=new Service(); //Constructor Dependency Injection
}
public void doPost(){
service.test(); //NullPointerException
}
}
public Service{
test(){ }
}
SPRING FRAMEWORK
DAY 5:
Bean Life Cycle

->it refers to the series of steps a bean goes through from


loading to destruction

init method through pure xml


in case of prototype scope you need to call
destroy method explictly
package com.mainapp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

EmployeeBean bean1=(EmployeeBean) ac.getBean("emp");


bean1.test();
EmployeeBean bean2=(EmployeeBean) ac.getBean("emp");
bean2.test();

EmployeeBean bean3=(EmployeeBean) ac.getBean("emp");


bean3.test();

ac.close();
}
}
package com.mainapp;
public class EmployeeBean {

static
{
System.out.println("BEAN LOADING");
}
public EmployeeBean()
{
System.out.println("BEAN INSTANTIATION");
}

public void myXmlInit() {


System.out.println("RESOURCE ALLOCATION");
}

public void test() {


System.out.println("CUSTOM METHOD");
}

public void myXmlDestroy() {


System.out.println("RESOURCE DE-ALLOCATION");
}
}

<?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <!-- bean definitions here -->

<bean
id="emp"
class="com.mainapp.EmployeeBean"
init-method="myXmlInit"
destroy-method="myXmlDestroy"
scope="prototype"
> </bean>

</beans>

For Annotation and Callback Interface you need


on extra jar aop.jar
PostConstruct ( Java Specification )
PreDestroy ( Java Specification )
From Java 1.9 these annotation has been remove and since java
1.9 onwards you have to download external jar javax
annotation jar

SPRING FRAMEWORK
DAY 6:
CallBack Interface ( Less
Common )
IntializingBean DisposableBean
package com.mainapp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new
ClassPathXmlApplicationContext("bean.xml");

EmployeeBean bean1=(EmployeeBean) ac.getBean("emp");


bean1.test();

ac.close();
}
}
package com.mainapp;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class EmployeeBean implements InitializingBean,DisposableBean {

static {
System.out.println("BEAN LOADING");
}

public EmployeeBean() {
System.out.println("BEAN INSTANTIATION");
}

public void myXmlInit() {


System.out.println("RESOURCE ALLOCATION-XML");
}

@PostConstruct
public void myAnnoInit() {
System.out.println("RESOURCE ALLOCATION-ANNO");
}

public void test() {


System.out.println("CUSTOM METHOD");
}

//init method
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("RESOURCE ALLOCATION-CALL");
}

//destroy
@Override
public void destroy() throws Exception {
System.out.println("RESOURCE DE-ALLOCATION-CALL");

public void myXmlDestroy() {


System.out.println("RESOURCE DE-ALLOCATION-XML");
}

@PreDestroy
public void myAnnoDestroy() {
System.out.println("RESOURCE DE-ALLOCATION-ANNO");
}

}
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <!-- bean
definitions here -->

<bean
id="emp"
class="com.mainapp.EmployeeBean"
init-method="myXmlInit"
destroy-method="myXmlDestroy"
> </bean>
<bean

class="org.springframework.context.annotation.CommonAnnotationBeanPostProcess
or"
> </bean>

</beans>

Note:
RESOURCE ALLOCATION-ANNO
RESOURCE ALLOCATION-CALL
RESOURCE ALLOCATION-XML
Bean Instantiation:
Simple <bean> Tags
Static Factory Method
package com.mainapp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

EmployeeBean bean1=(EmployeeBean) ac.getBean("emp");


bean1.test();

ac.close();
}
}
package com.mainapp;

import java.util.Scanner;

public class EmployeeBean {

private String companyCode;

static {
System.out.println("BEAN LOADING");
}

public EmployeeBean(String companyCode) {


this.companyCode=companyCode;
System.out.println("BEAN INSTANTIATION");
}

public void test() {


System.out.println("CUSTOM METHOD: "+companyCode);
}

public static EmployeeBean customObject() {


Scanner scanner = new Scanner(System.in);
System.out.println("ENTER KEY");

EmployeeBean employeeBean;
int key=scanner.nextInt();
if(key==1212) {
employeeBean=new EmployeeBean("QWERTY");
}
else {
employeeBean=new EmployeeBean("PQRS");
}

return employeeBean;
}

}
<?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <!-- bean definitions here -->

<!-- <bean
id="emp"
class="com.mainapp.EmployeeBean"
>

<constructor-arg name="companyCode" value="QWERTY">


enter key: correct->QWERY otherwise PQRS
</constructor-arg>

</bean> -->

<bean
id="emp"
class="com.mainapp.EmployeeBean"
factory-method="customObject"
>
</bean>

<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"
>
</bean>

</beans>

Factory class
package com.mainapp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

EmployeeBean bean1=(EmployeeBean) ac.getBean("emp");


bean1.test();

ac.close();
}
}
package com.mainapp;
import java.util.Scanner;
public class EmployeeBean {

private String companyCode;

static {
System.out.println("BEAN LOADING");
}
public EmployeeBean(String companyCode) {
this.companyCode=companyCode;
System.out.println("BEAN INSTANTIATION");
}

public void test() {


System.out.println("CUSTOM METHOD: "+companyCode);
}
}
package com.mainapp;
import java.util.Scanner;
public class ObjectFactoryClass {

public EmployeeBean customObject() {


Scanner scanner = new Scanner(System.in);
System.out.println("ENTER KEY");

EmployeeBean employeeBean;
int key=scanner.nextInt();
if(key==1212) {
employeeBean=new EmployeeBean("QWERTY");
}
else {
employeeBean=new EmployeeBean("PQRS");
}

return employeeBean;
}

<?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <!-- bean definitions here -->

<bean id="fbean" class="com.mainapp.ObjectFactoryClass" ></bean>

<bean
id="emp"
class="com.mainapp.EmployeeBean"
factory-bean="fbean"
factory-method="customObject"
>
</bean>

<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"
>
</bean>

</beans>
SPRING FRAMEWORK
DAY 7:
BeanPostProcessor(Interface)
 Bean Loading
 Bean Instantiation
postProcessBeforeInitialization(); //LOG
 init()
postProcessAfterInitialization(); //LOG
 Custom method
 destroy()

SPRING FRAMEWORK
DAY 8:
Bean Inheritance
<bean> : 5 property
<bean>: child
<bean>: child
<bean>: child

SPRING FRAMEWORK
DAY 9:
Dependency Injection in XML
1.setter injection <property> Ex. Primitive,String(value)
UserDefinedObj(ref)
2.constructor injection <constructor-agr> Ex.
Primitive,String(value) UserDefinedObj(ref)

Collection Injection
List injection:
1.List of inbuilt class object Ex. List<String> listOfBooks;
(Default Impl : ArrayList)
Through Setter:
package com.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Launch {

public static void main(String[] args) {


// TODO Auto-generated method stub

ClassPathXmlApplicationContext ac = new
ClassPathXmlApplicationContext("bean.xml");
Employee employee= (Employee) ac.getBean("employee");
employee.setEid(11);
employee.setEname("Raju");
employee.setEaddress("add1");

System.out.println(employee);
System.out.println(employee.getDeafultListOfBooks().getClass());
}
}
package com.test;
import java.util.List;

public class Employee {

//USER
private int eid;
private String ename;
private String eaddress;

private List<String> deafultListOfBooks; //DEPENDENCY

public Employee() {
// TODO Auto-generated constructor stub
}

public int getEid() {


return eid;
}

public void setEid(int eid) {


this.eid = eid;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public String getEaddress() {


return eaddress;
}

public void setEaddress(String eaddress) {


this.eaddress = eaddress;
}

public List<String> getDeafultListOfBooks() {


return deafultListOfBooks;
}

public void setDeafultListOfBooks(List<String> deafultListOfBooks) {


this.deafultListOfBooks = deafultListOfBooks;
}

@Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ", eaddress=" + eaddress + ",
deafultListOfBooks="
+ deafultListOfBooks + "]";
}
}

<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <!-- bean definitions here -->
<bean id="employee" class="com.test.Employee" >
<property name="deafultListOfBooks">
<list>
<value>JAVA</value>
<value>PYTHON</value>
<value>AI</value>
</list>
</property>
</bean>
</beans>

Through Constructor:
employee.java
public Employee(List<String> deafultListOfBooks) {
super();
this.deafultListOfBooks = deafultListOfBooks;
}
bean.xml
<bean id="employee" class="com.test.Employee" >
<constructor-arg name="deafultListOfBooks">
<list>
<value>JAVA</value>
<value>PYTHON</value>
<value>AI</value>
</list>
</constructor-arg>
</bean>

Own Implementation
1.StandAlone List (for setter you can use <property> tag
inside employee <bean>
<bean id="employee" class="com.test.Employee">
<constructor-arg name="deafultListOfBooks" ref="list">
</constructor-arg>

</bean>
<!-- STANDALONE LIST -->
<util:list id="list" list-class="java.util.LinkedList">
<value>JAVA</value>
<value>PYTHON</value>
<value>AI</value>
</util:list>

2.Seperate Bean Tag(Custom Collection)


<bean id="employee" class="com.test.Employee">
<constructor-arg name="deafultListOfBooks" ref="list" >
</constructor-arg>
</bean>

<bean id="list" class="java.util.LinkedList">


<constructor-arg>
<list>
<value>JAVA</value>
<value>PYTHON</value>
<value>PHP</value>
</list>
</constructor-arg>
</bean>

Note:
// ArrayList<String> arrayList = new ArrayList<String>();
// arrayList.add("test1");
// arrayList.add("test2");
// arrayList.add("test3");
//
// LinkedList<String> linkedList = new
LinkedList<String>(arrayList);
// System.out.println(linkedList);

// LinkedList<String> linkedList = new


LinkedList<String>(Arrays.asList("TEST1","TEST2","TEST3"));
// System.out.println(linkedList);

2.List of user defined class object Ex.


List<Account> listOfAccounts;
(Default Impl : ArrayList)
Through Setter:
package com.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Launch {

public static void main(String[] args) {


// TODO Auto-generated method stub

ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");


Employee employee= (Employee) ac.getBean("employee");
employee.setEid(11);
employee.setEname("Raju");
employee.setEaddress("add1");

System.out.println(employee);
System.out.println(employee.getDefaultListOfAccounts().getClass());
}
}
package com.test;

public class Account {

//IOC
private int an;
private String aname;

public Account() {
// TODO Auto-generated constructor stub
}

public Account(int an, String aname) {


super();
this.an = an;
this.aname = aname;
}

public int getAn() {


return an;
}

public void setAn(int an) {


this.an = an;
}

public String getAname() {


return aname;
}

public void setAname(String aname) {


this.aname = aname;
}

@Override
public String toString() {
return "Account [an=" + an + ", aname=" + aname + "]";
}
}
package com.test;
import java.util.List;

public class Employee {

//USER
private int eid;
private String ename;
private String eaddress;
//IOC
private List<Account> defaultListOfAccounts; //DEPENDENCY

public Employee() {
// TODO Auto-generated constructor stub
}

public Employee(List<Account> defaultListOfAccounts) {


super();
this.defaultListOfAccounts = defaultListOfAccounts;
}

public int getEid() {


return eid;
}

public void setEid(int eid) {


this.eid = eid;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public String getEaddress() {


return eaddress;
}

public void setEaddress(String eaddress) {


this.eaddress = eaddress;
}

public List<Account> getDefaultListOfAccounts() {


return defaultListOfAccounts;
}

public void setDefaultListOfAccounts(List<Account> defaultListOfAccounts) {


this.defaultListOfAccounts = defaultListOfAccounts;
}

@Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ", eaddress=" + eaddress + ",
defaultListOfAccounts="
+ defaultListOfAccounts + "]";
}
}

<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-
util.xsd"> <!-- bean definitions here -->

<bean id="acc1" class="com.test.Account">


<constructor-arg name="an" value="9090" ></constructor-arg>
<constructor-arg name="aname" value="bank1" ></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080" ></constructor-arg>
<constructor-arg name="aname" value="bank2" ></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<property name="defaultListOfAccounts">
<list>
<ref bean="acc1" />
<ref bean="acc2" />
</list>
</property>
</bean>

</beans>

Through Constructor:
<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090" ></constructor-arg>
<constructor-arg name="aname" value="bank1" ></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080" ></constructor-arg>
<constructor-arg name="aname" value="bank2" ></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<constructor-arg name="defaultListOfAccounts">
<list>
<ref bean="acc1" />
<ref bean="acc2" />
</list>
</constructor-arg>
</bean>

Own implementation:
1.StandAlone list: (for Setter you can use
<property> tag inside employee <bean> tag
<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090" ></constructor-
arg>
<constructor-arg name="aname" value="bank1"
></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080" ></constructor-
arg>
<constructor-arg name="aname" value="bank2"
></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<constructor-arg name="defaultListOfAccounts"
ref="list" ></constructor-arg>
</bean>

<util:list id="list" list-class="java.util.LinkedList" >


<ref bean="acc1" />
<ref bean="acc2" />
</util:list>

2.Seperate Bean Tag (Custom Collection)


<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090" ></constructor-
arg>
<constructor-arg name="aname" value="bank1"
></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080" ></constructor-
arg>
<constructor-arg name="aname" value="bank2"
></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<constructor-arg name="defaultListOfAccounts"
ref="list" ></constructor-arg>
</bean>

<bean id="list" class="java.util.LinkedList" >


<constructor-arg>
<list>
<ref bean="acc1" />
<ref bean="acc2" />
</list>
</constructor-arg>
</bean>
SPRING FRAMEWORK
DAY 10:
Dependency Injection in XML
Collection Injection
Set Injection:
1. Set of predefined class Object Ex. Set<String>
 By default it will inject LinkedHashSet (Order:
Preserved) : setter/getter
 Own impl( Ex. HashSet )
 a.StandAlone Set : setter/getter
 b.Seperate bean tag : setter/getter
2. Set of user defined class Object Ex. Set<Account>
 By default it will inject LinkedHashSet (Order:
Preserved) : setter/getter
 Own impl( Ex. HashSet )
 a.StandAlone Set : setter/getter
 b.Seperate bean tag : setter/getter
Program:
package com.test;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;
public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new
ClassPathXmlApplicationContext("bean.xml");
Employee employee= (Employee) ac.getBean("employee");

employee.setId(18);
employee.setName("raju");
employee.setAddress("add1");

System.out.println(employee);

System.out.println(employee.getSetOfDefaultBooks().getClass());

}
}
package com.test;
import java.util.Set;

public class Employee {

//USER
private int id;
private String name;
private String address;

//IOC
private Set<String> setOfDefaultBooks;

public Employee() {

public Employee(Set<String> setOfDefaultBooks) {


super();
this.setOfDefaultBooks = setOfDefaultBooks;
}
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 getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

public Set<String> getSetOfDefaultBooks() {


return setOfDefaultBooks;
}

public void setSetOfDefaultBooks(Set<String>


setOfDefaultBooks) {
this.setOfDefaultBooks = setOfDefaultBooks;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ",
address=" + address + ", setOfDefaultBooks="
+ setOfDefaultBooks + "]";
}
}

<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- bean definitions here -->

<bean id="employee" class="com.test.Employee">


<property name="setOfDefaultBooks">
<set>
<value>JAVA</value>
<value>JAVAABC</value>
<value>ABCJAVA</value>
<value>JAVABBB</value>
<value>JAYYYVA</value>
<value>JPPPAVA</value>
</set>
</property>
</bean>
</beans>

Through constructor:
<bean id="employee" class="com.test.Employee">
<constructor-arg name="setOfDefaultBooks">
<set>
<value>JAVA</value>
<value>JAVAABC</value>
<value>ABCJAVA</value>
<value>JAVABBB</value>
<value>JAYYYVA</value>
<value>JPPPAVA</value>
</set>
</constructor-arg>
</bean>

Own impl:
1.StandAlone:
Through constructor
<bean id="employee" class="com.test.Employee">
<constructor-arg name="setOfDefaultBooks" ref="set">
</constructor-arg>
</bean>

<util:set id="set" set-class="java.util.HashSet">


<value>JAVA</value>
<value>JAVAABC</value>
<value>ABCJAVA</value>
<value>JAVABBB</value>
<value>JAYYYVA</value>
<value>JPPPAVA</value>
</util:set>

Through Setter:
<bean id="employee" class="com.test.Employee">
<property name="setOfDefaultBooks" ref="set">
</property>
</bean>
<util:set id="set" set-class="java.util.HashSet">
<value>JAVA</value>
<value>JAVAABC</value>
<value>ABCJAVA</value>
<value>JAVABBB</value>
<value>JAYYYVA</value>
<value>JPPPAVA</value>
</util:set>

2. Separate Bean Tag(Custom Collection)


<bean id="employee" class="com.test.Employee">
<property name="setOfDefaultBooks" ref="set">
</property>
</bean>

<bean id="set" class="java.util.HashSet">


<constructor-arg>
<set>
<value>JAVA</value>
<value>JAVAABC</value>
<value>ABCJAVA</value>
<value>JAVABBB</value>
<value>JAYYYVA</value>
<value>JPPPAVA</value>
</set>
</constructor-arg>
</bean>

Note:
<bean id="employee" class="com.test.Employee">
<property name="setOfDefaultBooks" ref="set">
</property>
</bean>

<bean id="set" class="java.util.HashSet">


<constructor-arg>
<list>
<value>JAVA</value>
<value>JAVAABC</value>
<value>ABCJAVA</value>
<value>JAVABBB</value>
<value>JAYYYVA</value>
<value>JPPPAVA</value>
</list>
</constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<property name="setOfDefaultBooks" ref="set">
</property>
</bean>

<bean id="set" class="java.util.HashSet">


<constructor-arg>
<array>
<value>JAVA</value>
<value>JAVAABC</value>
<value>ABCJAVA</value>
<value>JAVABBB</value>
<value>JAYYYVA</value>
<value>JPPPAVA</value>
</array>
</constructor-arg>
</bean>

=======================================
=============================
Set of user defined class object
1.default impl(setter)
package com.test;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;
public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new
ClassPathXmlApplicationContext("bean.xml");
Employee employee= (Employee) ac.getBean("employee");

employee.setId(18);
employee.setName("raju");
employee.setAddress("add1");

System.out.println(employee);

System.out.println(employee.getSetOfAccounts().getClass());

}
}
package com.test;
import java.util.Set;

public class Employee {

//USER
private int id;
private String name;
private String address;

//IOC
private Set<Account> setOfAccounts;

public Employee() {

public Employee(Set<Account> setOfAccounts) {


super();
this.setOfAccounts = setOfAccounts;
}

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 getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}
public Set<Account> getSetOfAccounts() {
return setOfAccounts;
}

public void setSetOfAccounts(Set<Account> setOfAccounts) {


this.setOfAccounts = setOfAccounts;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ",
address=" + address + ", setOfAccounts=" + setOfAccounts
+ "]";
}
}
package com.test;

public class Account {

//IOC
private int an;
private String aname;

public Account() {
// TODO Auto-generated constructor stub
}

public Account(int an, String aname) {


super();
this.an = an;
this.aname = aname;
}

public int getAn() {


return an;
}

public void setAn(int an) {


this.an = an;
}

public String getAname() {


return aname;
}
public void setAname(String aname) {
this.aname = aname;
}

@Override
public String toString() {
return "Account [an=" + an + ", aname=" + aname + "]";
}
}
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- bean definitions here -->

<bean id="acc1" class="com.test.Account">


<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080"></constructor-
arg>
<constructor-arg name="aname"
value="bank2"></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<property name="setOfAccounts">
<set>
<ref bean="acc1" />
<ref bean="acc2" />
</set>
</property>
</bean>
</beans>
2.default impl(constructor) : use constructor-
arg tag with employee <bean>
<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080"></constructor-
arg>
<constructor-arg name="aname"
value="bank2"></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<constructor-arg name="setOfAccounts">
<set>
<ref bean="acc1" />
<ref bean="acc2" />
</set>
</constructor-arg>
</bean>

MyOwn Impl( HashSet)


1.StandAlone Set (Through constructor)
<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080"></constructor-
arg>
<constructor-arg name="aname"
value="bank2"></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<constructor-arg name="setOfAccounts" ref="set">
</constructor-arg>
</bean>

<util:set id="set" set-class="java.util.HashSet">


<ref bean="acc1" />
<ref bean="acc2" />
</util:set>

For setter use property tag with employee bean

2.Seperate Bean Tag (constructor)


<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080"></constructor-
arg>
<constructor-arg name="aname"
value="bank2"></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<constructor-arg name="setOfAccounts" ref="set">
</constructor-arg>
</bean>

<bean id="set" class="java.util.HashSet">


<constructor-arg>
<set>
<ref bean="acc1" />
<ref bean="acc2" />
</set>
</constructor-arg>
</bean>

For setter use property tag with employee bean

MAP INJECTION:
1. Map of predefined class Object Ex. Map<String,String>
 By default it will inject LinkedHashMap (Order:
Preserved) : setter/getter
 Own impl( Ex. HashMap )
 a.StandAlone Map : setter/getter
 b.Seperate bean tag : setter/getter
2. Set of user defined class Object Ex. Map<String,Account>
 By default it will inject LinkedHashMap (Order:
Preserved) : setter/getter
 Own impl( Ex. HashMap )
 a.StandAlone Map : setter/getter
 b.Seperate bean tag : setter/getter

Program: Map of predefined class Object Ex.


Map<String,String>
Default impl(Setter)
package com.test;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;
public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new
ClassPathXmlApplicationContext("bean.xml");
Employee employee= (Employee) ac.getBean("employee");

employee.setId(18);
employee.setName("raju");
employee.setAddress("add1");

System.out.println(employee);
System.out.println(employee.getMapOfBooks().getClass());
}
}
package com.test;
import java.util.Map;
public class Employee {

//USER
private int id;
private String name;
private String address;

//IOC
private Map<String,String> mapOfBooks;

public Employee() {

public Employee(Map<String, String> mapOfBooks) {


super();
this.mapOfBooks = mapOfBooks;
}

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 getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

public Map<String, String> getMapOfBooks() {


return mapOfBooks;
}

public void setMapOfBooks(Map<String, String> mapOfBooks) {


this.mapOfBooks = mapOfBooks;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ",
address=" + address + ", mapOfBooks=" + mapOfBooks + "]";
}

<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- bean definitions here -->

<bean id="employee" class="com.test.Employee">


<property name="mapOfBooks">
<map>
<entry key="a1" value="java1" ></entry>
<entry key="a2" value="java2" ></entry>
<entry key="a3" value="java3" ></entry>
<entry key="a4" value="java4" ></entry>
</map>
</property>
</bean>

</beans>
Through constructor: use constructor-arg tag with employee
bean

Own impl:
1.StandAlone Map: (Setter)
<bean id="employee" class="com.test.Employee">
<property name="mapOfBooks" ref="map">
</property>
</bean>

<util:map id="map" map-class="java.util.HashMap" >


<entry key="a1" value="java1"></entry>
<entry key="a2" value="java2"></entry>
<entry key="a3" value="java3"></entry>
<entry key="a4" value="java4"></entry>
</util:map>

Through constructor: use constructor-arg tag with employee


bean
2.Seperate Bean Tag: (Setter)
<bean id="employee" class="com.test.Employee">
<property name="mapOfBooks" ref="map">
</property>
</bean>

<bean id="map" class="java.util.HashMap">


<constructor-arg>
<map>
<entry key="a1" value="java1"></entry>
<entry key="a2" value="java2"></entry>
<entry key="a3" value="java3"></entry>
<entry key="a4" value="java4"></entry>
</map>
</constructor-arg>
</bean>
Through constructor: use constructor-arg tag with employee
bean

2. Set of user defined class Object Ex.


Map<String,Account>
1.default (Setter)
Key: predefined : key
Key: userDefined : key-ref
Value: predefined : value
Value: userDefined: value-ref
package com.test;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;
public class Launch {

public static void main(String[] args) {

ClassPathXmlApplicationContext ac = new
ClassPathXmlApplicationContext("bean.xml");
Employee employee= (Employee) ac.getBean("employee");

employee.setId(18);
employee.setName("raju");
employee.setAddress("add1");

System.out.println(employee);

System.out.println(employee.getMapOfAccounts().getClass());
}
}
package com.test;
import java.util.Map;
public class Employee {

//USER
private int id;
private String name;
private String address;

//IOC
private Map<String,Account> mapOfAccounts; //<
key=preDefined , value=userDefined >

public Employee() {

public Employee(Map<String, Account> mapOfAccounts) {


super();
this.mapOfAccounts = mapOfAccounts;
}

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 getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

public Map<String, Account> getMapOfAccounts() {


return mapOfAccounts;
}

public void setMapOfAccounts(Map<String, Account>


mapOfAccounts) {
this.mapOfAccounts = mapOfAccounts;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ",
address=" + address + ", mapOfAccounts=" + mapOfAccounts
+ "]";
}
}

<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- bean definitions here -->
<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080"></constructor-
arg>
<constructor-arg name="aname"
value="bank2"></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<property name="mapOfAccounts">
<map>
<entry key="a1" value-ref="acc1"></entry>
<entry key="a2" value-ref="acc2"></entry>
</map>
</property>
</bean>
</beans>

Through constructor: use constructor-arg tag with employee


bean

Own Impl:
1.StandAlone(Setter)
<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080"></constructor-
arg>
<constructor-arg name="aname"
value="bank2"></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<property name="mapOfAccounts" ref="map">
</property>
</bean>

<util:map id="map" map-class="java.util.HashMap">


<entry key="a1" value-ref="acc1"></entry>
<entry key="a2" value-ref="acc2"></entry>
</util:map>
Through constructor: use constructor-arg tag with employee
bean

2.Seperate Bean Tag(Custom Collection)


<bean id="acc1" class="com.test.Account">
<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="acc2" class="com.test.Account">


<constructor-arg name="an" value="8080"></constructor-
arg>
<constructor-arg name="aname"
value="bank2"></constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee">


<property name="mapOfAccounts" ref="map">
</property>
</bean>

<bean id="map" class="java.util.HashMap">


<constructor-arg>
<map>
<entry key="a1" value-ref="acc1"></entry>
<entry key="a2" value-ref="acc2"></entry>
</map>
</constructor-arg>
</bean>
Through constructor: use constructor-arg tag with employee
bean

Exceptional Case:
Key: Integer (LinkedHashMap only, map-class
wont work)
=======================================
=========================

SPRING FRAMEWORK
DAY 11:
Dependency Injection in XML
Autowiring through XML
->It is a way of dependency injection in which
dependency will inject automatically
Modes:
1.No (Manually injection)
2.byName (Setter)
3.byType (Setter)
4.constructor ( Constructor )
Not Suitable for Complex Configuration
Not Readable

bean.xml
<bean id=”eid” class=”com.test.Employee”
autowire=”byName”>
</bean>
<bean id=”account” >
<util:list id=”listofbooks” class=”linkedlist”>
<util:list id=”listofbooks2” class=”vector”>

byname:
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- bean definitions here -->

<bean id="account" class="com.test.Account">


<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="adhaar" class="com.test.Adhaar">


<constructor-arg name="adhaarNo"
value="11119090"></constructor-arg>
<constructor-arg name="adhaarName"
value="raju"></constructor-arg>
</bean>

<bean id="listOfBooks" class="java.util.LinkedList" >


<constructor-arg>
<list>
<value>JAVA1</value>
<value>JAVA2</value>
<value>JAVA3</value>
</list>
</constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee"


autowire="byName">

</bean>

</beans>
In case of byname if there is two bean
available and we are looking for a single bean
then in such case we can disqualify a bean by
autowire-candidate=”false” , still it will be
available for manual injection and autowire
byname injection

<bean id="bean1a" class="com.test.Account">


<constructor-arg name="an" value="9090"></constructor-
arg>
<constructor-arg name="aname"
value="bank1"></constructor-arg>
</bean>

<bean id="bean1b" class="com.test.Account">


<constructor-arg name="an"
value="90902"></constructor-arg>
<constructor-arg name="aname"
value="bank2"></constructor-arg>
</bean>

<bean id="bean1c" class="com.test.Account">


<constructor-arg name="an"
value="90903"></constructor-arg>
<constructor-arg name="aname"
value="bank3"></constructor-arg>
</bean>

<bean id="bean1d" class="com.test.Account">


<constructor-arg name="an"
value="90904"></constructor-arg>
<constructor-arg name="aname"
value="bank4"></constructor-arg>
</bean>

<bean id="bean1e" class="com.test.Account">


<constructor-arg name="an"
value="90905"></constructor-arg>
<constructor-arg name="aname"
value="bank5"></constructor-arg>
</bean>

<bean id="bean1f" class="com.test.Account" primary="true">


<constructor-arg name="an"
value="90906"></constructor-arg>
<constructor-arg name="aname"
value="bank6"></constructor-arg>
</bean>

<bean id="bean2" class="com.test.Adhaar">


<constructor-arg name="adhaarNo"
value="11119090"></constructor-arg>
<constructor-arg name="adhaarName"
value="raju"></constructor-arg>
</bean>

<bean id="listbean1" class="java.util.LinkedList" >


<constructor-arg>
<list>
<value>JAVA1</value>
<value>JAVA2</value>
<value>JAVA3</value>
</list>
</constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee"


autowire="byType"> <!--Account , Adhaar , List -->
</bean>

Mode3: constructor (ByType->ByName) :


Through constructor
Exception : Constructor Common: 1fail: All fail
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- bean definitions here -->

<bean id="bean1a" class="com.test.Account">


<property name="an" value="90901"></property>
<property name="aname" value="bank1"></property>
</bean>

<bean id="bean1b" class="com.test.Account">


<property name="an" value="90902"></property>
<property name="aname" value="bank2"></property>
</bean>

<bean id="bean1c" class="com.test.Account">


<property name="an" value="90903"></property>
<property name="aname" value="bank3"></property>
</bean>

<bean id="bean1d" class="com.test.Account">


<property name="an" value="90904"></property>
<property name="aname" value="bank4"></property>
</bean>

<bean id="bean1e" class="com.test.Account">


<property name="an" value="90905"></property>
<property name="aname" value="bank5"></property>
</bean>

<bean id="account" class="com.test.Account">


<property name="an" value="90906"></property>
<property name="aname" value="bank6"></property>
</bean>

<bean id="adhaar" class="com.test.Adhaar">


<property name="adhaarNo" value="11119090"></property>
<property name="adhaarName" value="raju"></property>
</bean>

<bean id="list1" class="java.util.LinkedList" >


<constructor-arg>
<list>
<value>JAVA1</value>
<value>JAVA2</value>
<value>JAVA3</value>
</list>
</constructor-arg>
</bean>

<bean id="listOfBooks" class="java.util.LinkedList" >


<constructor-arg>
<list>
<value>JAVA1</value>
<value>JAVA2</value>
<value>JAVA3</value>
</list>
</constructor-arg>
</bean>

<bean id="employee" class="com.test.Employee"


autowire="constructor"> <!--Account , Adhaar , List -->
</bean>

</beans>
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
F
z
z

You might also like