Spring Course Material Nagoor Babu
Spring Course Material Nagoor Babu
SPRING
COURSE MATERIAL
BY
NAGOOR BABU
{ SPRING ORM}
1
e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
2
e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
1. Spring ORM…………………………………..……………………………..….…..PAGE 04
2. Application on Spring-Hibernate integration………..…………..…..PAGE 12
3. JPA[Java Persistence API]…………………………………………….………PAGE 18
4. Integration of JPA with Spring application in ORM Module ……PAGE 32
3
e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Spring ORM
Spring ORM:
In enterprise applications both the data models are having their own approaches to represent data
in effective manner, these differences are able to provide Paradiagm Mismatches, these
mismatches are able to reduce data persistency in ent erprise applications.
In general, Object Oriented Data Model and Relational data model are
are having the following
mismatches.
1. Granualarity Mismatch
2. Sub types mismatch
3. Associations Mismatch
4. Identity Mismatch
To improve Data persistency in Enterprise applications we have to resolve the above specified
mismtahces between Data models, for this, we have to use "ORM" implementations.
To implement ORM in Enterprise applications we have to use the following ORM implementations.
1. EJBs-Entity Beans
2. JPA
3. Hibernate
4. IBatis
5. JDO
If we want to use Hibernate in enterprise applications then we have to use the following sateps.
1) Persistence Class or Object.
Object.
2) Prepare Mapping File.
3) Prepare Hibernate Configuration File
4) Prepare Hibernate Client Application
Example:
1. Configuration cfg
cfg =
= new
new Configuration();
Configuration();
2. cfg.configure("hibernate.cfg.xml"); 4
e
g
3. SessionFactory session_Factory
session_Factory =
= cfg
cfg.buildSessionFactory();
.buildSessionFactory(); a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
To remove the above boilerplate code, SPRING Framework has provided ORM Module.
Spring has provided the complete ORM module in
i n the form of "org.springframework.orm"
package.
Note: If
Note: If we use Hibernate3.x version then we have to use
"org.springframework.orm.hibernate3.HibernateTemplate"
"org.springframework.orm.hibernate3 .HibernateTemplate" class.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
1. Create Java Project with both Spring[including ORM] and Hibernate Libraries.
Prepare JAVA project in Eclipse IDE and add the following JAR files to Buildpath in the form of the
following Libraries.
Spring4_Lib:
spring-aop-4.0.4.RELEASE.jar
spring-beans-4.0.4.RELEASE.jar
spring-context-4.0.4.RELEASE.jar
spring-context-support-4.0.4.RELEASE.jar
spring-core-4.0.4.RELEASE.jar
spring-expression-4.0.4.RELEASE.jar
spring-jdbc-4.0.4.RELEASE.jar
commons-io-2.6.jar
commons-logging-1.2.jar
spring-tx-4.0.4.RELEASE.jar
spring-aspects-4.0.4.RELEASE.jar
spring-orm-4.0.4.RELEASE.jar
Hibernate4_Lib:
ojdbc6.jar
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-logging-annotation s-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jboss-transaction-api_1.2_s pec-1.0.0.Final.jar
hibernate-entitymanager-4.3.11.Final.jar
1. public class
class Student{
Student{
2. private String
private String sid;
3. private String
private String sname;
4. private String
private String saddr;
5. setXXX() and getXXX() 6
6. } e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Student.hbm.xml
EX:
1. public interface
interface StudentDao
StudentDao {
2. public String
public String insert(Student std);
3. public String
public String update(Student std);
4. public String
public String delete(Student std);
5. public Employee
public Employee getStudent(int
getStudent(int eno);
eno);
6. }
The main intention of DAO implementation class is to implement all DAO methods. In DAO
implementation class everyevery DAO method must be declared
declared with @Transactional annotation
annotation
inorder to activate Spring Transaction Service.
Note: If we use @Transactional annotation then it is not required to create Transaction object
explicitly and iit is not required to perform commit and rollback operations explicitly.
In DAO implementation class we must declare HibernateTemplate property and its respective
setXXX() method inorder to inject
i nject HibernateTemplate object.
Example:
1. public class
class StudentDaoImpl
StudentDaoImpl implements
implements StudentDao
StudentDao {
2. String status = ""
"";;
3. private HibernateTemplate
private HibernateTemplate hibernateTemplate; 7
e
4. public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
void setHibernateTemplate(HibernateTemplate g
a
5. this.hibernateTemplate
this.hibernateTemplate = hibernateTemplate; P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Where org.springframework.jdbc.datas
org.springframework.jdbc.datasource.DriverManagerD
ource.DriverManagerDataSource
ataSource configuration is
able to provide Spring inbuilt Connectionpooling
Connectionpooling Mechanism and it will include the
properties liike "driverClassName, url, username, password".
Where org.springframework.orm.hibernate4.Lo
org.springframework.orm.hibernate4.LocalSessionFactory
calSessionFactoryBean
Bean configuration
configuration is able
to create SessionFactory object by including the properties like
1. dataSource : represents DataSource bean which was configured in Spring
Configuration file.
2. mappingResources: It will take list of values contains mapping files in the
form of "<list>" tag.
3. hibernateProperties:
hibernateProperties: It will take hibernate properties in the form of
"<props>" tag, it must includes mainly "hibernate.dialect" property.
Where org.springframework.orm.hibernate4
org.springframework.orm.hibernate4.HibernateTransactionMa
.HibernateTransactionManager
nager configuration
will activate Transaction Manager inorder to provide Tr ansaction Support and it will include
"sessionFactory" property.
Where org.springframework.orm.hibernate4.Hibern
org.springframework.orm.hibernate4.HibernateTemplate
ateTemplate configuration will provide
HibernateTemplate object inorder to perform persistence operations and it will include
"sessionFactory" and "checkWriteOperations" with false value.
Where com.durgasoft.dao.StudentDaoImpl
com.durgasoft.dao.StudentDaoImpl configuration
configuration will provide
provide DAO object
object inorder to
access Dao methods and it will include "hibernateTemplate" property.
Note: To use @Transactional
Note: To @Transactional annotation in DAO methods , wewe must use " <tx:annotation- 9
driven/>" tag in spring configuration file. e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
applicationContext.xml
1. <?xml version
version= ="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>?>
2. <beans xmlns
xmlns= ="http://www.springframework.org/schema/beans"
3. xmlns:xsi=
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:aop=
xmlns:aop ="http://www.springframework.org/schema/aop"
5. xmlns:tx=
xmlns:tx ="http://www.springframework.org/schema/tx"
6. xsi:schemaLocation="
xsi:schemaLocation ="
7. http://www.springframework.org/schema/beans
8. http://www.springframework.org/schema/beans/spring-beans.xsd
9. http://www.springframework.org/schema/tx
10. http://www.springframework.org/schema/tx/spring-tx.xsd
11. http://www.springframework.org/schema/aop
12. http://www.springframework.org/schema/aop/spring-aop.xsd">
http://www.springframework.org/schema/aop/spring-aop.xsd" >
13.
14. <bean name
name= ="dataSource" class
class=="org.springframework.jdbc.datasource.DriverManagerD
ataSource">
ataSource" >
15. <property name name= ="driverClassName" value
value=
="oracle.jdbc.OracleDriver" />
/>
16. <property name name= ="url" value
value=
="jdbc:oracle:thin:@localhost:1521:xe" />
/>
17. <property name name= ="username" value
value=="system" />
/>
18. <property name name= ="password" value
value=="durga" />
/>
19. </bean>
20. <bean name
name= ="sessionFactory" class
class=
="org.springframework.orm.hibernate4.LocalSessionF
actoryBean">
actoryBean" >
21. <property name name= ="dataSource" ref ="dataSource" /> />
22. <property name name= ="mappingResources"
"mappingResources"> >
23. <list>
24. <value>Student.hbm.xml
<value> Student.hbm.xml</value>
</value>
25. </list>
26. </property>
27. <property name name= ="hibernateProperties"
"hibernateProperties"> >
28. <props>
29. <prop keykey=="hibernate.dialect"
"hibernate.dialect">>org.hibernate.dialect.Oracle10gDialect
org.hibernate.dialect.Oracle10gDialect</prop>
</prop>
30. <prop keykey=="hibernate.show_sql"
"hibernate.show_sql"> >true</prop>
true</prop>
31. </props>
32. </property>
33. </bean>
34. <tx:annotation-driven/>
0
35. <bean id id=
="transactionManager" classclass=="org.springframework.orm.hibernate4.HibernateTra 1
nsactionManager">
nsactionManager" > e
g
a
36. <property name
name= ="sessionFactory" ref ="sessionFactory" />
/> P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
The main intention of Client Application is to get Dao object and to access Dao object.
Example:
1. ApplicationContext context
context = = new ClassPathXmlApplicationCo
ClassPathXmlApplicationContext("applicationContex
ntext("applicationContext.xml
t.xml
");
2. StudentDao stdDao
stdDao = = (StudentDao)context.getBean("stdDao");
(StudentDao)context.getBean("stdDao");
3. Student std
std =
= new
new Student();
Student();
4. std.setSid("S-111");
5. std.setSname("AAA");
6. std.setSaddr("Hyd");
7. String status
status =
= stdDao
stdDao.insert(std);
.insert(std);
8. System.out.println(status);
9. or
10. Student std
std =
= (Student)stdDao.getStud
(Student)stdDao.getStudent(Student.class,"S-111");
ent(Student.class,"S-111");
11. System.out.println("Student Details");
12. System.out.println("--------------------");
13. System.out.println("Student Id :"+std.getSid());
14. System.out.println("Student Name :"+std.getSname());
15. System.out.println("Student Address :"+std.getSaddr());
16. or
17. Student std
std =
= new
new Student();
Student();
18. std.setSid("S-111");
19. std.setSname("BBB");
20. std.setSaddr("Hyd");
21. String status
status =
= stdDao
stdDao.update(std);
.update(std);
22. System.out.println(status);
1
23. or 1
24. String status
status =
= stdDao
stdDao.delete("S-111");
.delete("S-111"); e
g
a
25. System.out.println(status); P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Employee.java
1. package
package com.durgasoft.pojo;
com.durgasoft.pojo;
2.
3. public class
class Employee
Employee {
4. private int eno;
int eno;
5. private String
private String ename;
6. private float
float esal;
esal;
7. private String
private String eaddr;
8.
9. public int
int getEno()
getEno() {
10. return eno;
return eno;
11. }
12. public void
void setEno(
setEno(intint eno)
eno) {
13. this.eno
this.eno = eno;
14. }
15. public String getEname() {
public String
16. return ename;
return ename;
17. }
18. public void
void setEname(String
setEname(String ename) {
19. this.ename
this.ename = ename;
20. }
21. public float
float getEsal()
getEsal() {
22. esal;
return esal;
return
23. }
24. public void
void setEsal(
setEsal(float
float esal)
esal) {
25. this.esal
this.esal = esal;
26. }
27. public
public String
String getEaddr() {
28. return eaddr;
return eaddr;
29. }
30. public void
void setEaddr(String
setEaddr(String eaddr) {
31. this.eaddr
this.eaddr = eaddr;
32. }
33.
34. public
public String
String toString() { 2
1
35. return "["
"["+eno+
+eno+","","+ename+
+ename+"," ","+esal+
+esal+","
","+eaddr+
+eaddr+"]"
"]";; e
g
36. } a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
EmployeeDao.java
1. package
package com.durgasoft.dao;
com.durgasoft.dao;
2.
3. import
import com.durgasoft.pojo.Employee;
com.durgasoft.pojo.Employee;
4.
5. public interface
interface EmployeeDao
EmployeeDao {
6. public String
public String insert(Employee e);
7. public String
public String update(Employee e);
8. public String
public String delete(Employee e);
9. public Employee
public Employee getEmployee(int
getEmployee(int eno);
eno);
10. }
EmployeeDaoImpl.java
1. package
package com.durgasoft.dao;
com.durgasoft.dao;
2. import
import org.hibernate.FlushMode;
org.hibernate.FlushMode;
3. import
import org.hibernate.Transaction;
org.hibernate.Transaction;
4. import org.springframework.orm.hibernate4.
org.springframework.orm.hibernate4.HibernateTemplate;
HibernateTemplate;
5. import org.springframework.transaction.an
org.springframework.transaction.annotation.Transactional;
notation.Transactional;
6.
7. import
import com.durgasoft.pojo.Employee;
com.durgasoft.pojo.Employee;
8.
9. public class
class EmployeeDaoImpl
EmployeeDaoImpl implements
implements EmployeeDao
EmployeeDao {
10. String status = "" "";;
11. private
private HibernateTemplate
HibernateTemplate hibernateTemplate;
12. public void
void setHibernateTemplate(HibernateTemplate
setHibernateTemplate(HibernateTemplate hibernateTemplate) {
13. this.hibernateTemplate
this .hibernateTemplate = hibernateTemplate;
14.
15. }
16.
17. @Override
18. @Transactional
19. public
public String
String insert(Employee e) {
20. try {
try {
21. hibernateTemplate.save(e);
22. status = "Insertion Success";
Success";
3
23. }catch
catch(Exception
(Exception ex) { 1
e
24. ex.printStackTrace(); g
a
25. status = "Insertion Failure";
Failure"; P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
1. <?xml version
version=
="1.0" encoding
encoding=="UTF-8"
"UTF-8"?>?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
5. <hibernate-mapping>
6. <class name
name=="com.durgasoft.pojo.Employee" table
table=
="emp1"
"emp1">
>
7. <id name
name=="eno" column
column=="ENO" />
/>
8. <property name
name=="ename" column
column= ="ENAME" />
/>
9. <property name
name=="esal" column
column= ="ESAL" />
/>
10. <property name
name=="eaddr" column
column= ="EADDR" />
11. </class>
12. </hibernate-mapping>
applicationContext.xml
1. <?xml version
version=="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>?>
2. <beans xmlns
xmlns=="http://www.springframework.org/schema/beans"
3. xmlns:xsi=
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:aop=
xmlns:aop ="http://www.springframework.org/schema/aop"
5. xmlns:tx=
xmlns:tx ="http://www.springframework.org/schema/tx"
6. xsi:schemaLocation="
xsi:schemaLocation ="
7. http://www.springframework.org/schema/beans
8. http://www.springframework.org/schema/beans/spring-beans.xsd
9. http://www.springframework.org/schema/tx
10. http://www.springframework.org/schema/tx/spring-tx.xsd
11. http://www.springframework.org/schema/aop
12. http://www.springframework.org/schema/aop/spring-aop.xsd">
http://www.springframework.org/schema/aop/spring-aop.xsd" >
13.
14.
15. <bean name
name= ="dataSource" class
class=="org.springframework.jdbc.datasource.DriverManagerD
ataSource">
ataSource" >
16. <property name name= ="driverClassName" value
value=="oracle.jdbc.OracleDriver" />
/>
17. <property name name= ="url" value
value=
="jdbc:oracle:thin:@localhost:1521:xe" />
/>
18. <property name name= ="username" value
value=
="system" />
/>
19. <property name name= ="password" value
value=="durga" />
/>
20. </bean>
21. <bean name
name= ="sessionFactory" class
class=
="org.springframework.orm.hibernate4.LocalSessionF
actoryBean">
actoryBean" >
5
22. <property name name= ="dataSource" ref ="dataSource" /> /> 1
e
23. <property name name= ="mappingResources"
"mappingResources"> > g
a
24. <list> P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Test.java
1. package
package com.durgasoft.test;
com.durgasoft.test;
2.
3. import org.springframework.contex
org.springframework.context.ApplicationContext;
t.ApplicationContext;
4. import org.springframework.contex
org.springframework.context.support.ClassPathXmlApplica
t.support.ClassPathXmlApplicationContext;
tionContext;
5. import org.springframework.orm.hibernate4.
org.springframework.orm.hibernate4.HibernateTemplate;
HibernateTemplate;
6.
7. import com.durgasoft.dao.Emplo
com.durgasoft.dao.EmployeeDao;
yeeDao;
8. import
import com.durgasoft.pojo.Employee;
com.durgasoft.pojo.Employee;
9.
10. public class
class Test
Test {
11.
6
12. public static voidvoid main(String[]
main(String[] args)throws
args)throws Exception
Exception { 1
13. ApplicationContext
ApplicationContext context = new ClassPathXmlApplica
ClassPathXmlApplicationContext(
tionContext("applicationConte
"applicationConte e
g
a
xt.xml");
xt.xml"); P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
7
1
e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Introduction:
JPA is a an API , it can be used to perform database
database operation
operations
s in enterprise applications
with ORM implementation tools.
JPA is a specification
specification provided by SUN Microsystems and
and it is implemented
implemented by some third
party vendors like JBOSS, Eclipse Foundations, Apache......
JPA is following
following ORM rules regulations to achieve data persistency in enterprise
applications and it is implemented by the following tools.
If we want to prepare JPA applications with "Hibernate" JPA provider then we have to use the
following steps.
1. Create Java project
project in Eclipse with JPA library which includes all Hibernate
Hibernate JARs.
2. Create Entity
Entity class under src folder.
3. Create mapping File or Use
Use JPA annotations
annotations in POJO class.
4. Create JPA configuration File[persistence.xml]
5. Create Test Application.
1. Create Java project in Eclipse with JPA library which includes all Hibernate JARs.
This step is same as Java project creation and it will include JPA provider Library that is Hibernate
jars.
Student.java
8
1. package com.durgasoft.entity;
package com.durgasoft.entity; 1
e
g
2. public class
class Student{
Student{ a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
It is same as Hibernate mapping file, it will provide mapping between Object Oriented Data model
elements like class, Id property, normal properties with the relational data model elements like
Table name, Primary Key Columns, normal columns,....
columns,....
EX:
Student.xml
1. <hibernate-mapping>
2. <class name
name=="com.durgasoft.entity.Student" table
table=
="student"
"student">
>
3. <id name
name=="sid" column
column=="SID" />
/>
4. <property name
name= ="sname" column
column=="SNAME" />
/>
5. <property name
name= ="saddr" column
column=="SADDR" />
/>
6. </class>
7. </hibernate-mapping>
JPA configuration File is same as Hibernate COnfiguration File, it include all JPA configuration
details which are required to interact with database .
IN general, we will provide the following configuration details in JPA configuration file.
1. Jdbc Parameters like Driver class name, Driver
Driver URL, Database
Database user name, Database
Database
password.
2. Dialect configurations
3. Mapping File or Annotated classes configuration
4. Cache Mechanisms configurations
5. Transactions configurations
Ex persistence.xml: 9
1
e
1. <persistence> g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Where <persistence>
<persistence> tag is root tag in JPA configuration File.
Where <mapping-file>
<mapping-file> tag is able to take mapping
mapping file configuration
where <propertis> tag will include JPA properties.
properties.
Where <property> tag will take a single JPA
JPA property like driver
driver class name, driver
driver url,....
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
EX: EntityManager
EX: EntityManager entManager = factory.createEntitymanag
f actory.createEntitymanager();
er();
EX: EntityTransaction
EX: EntityTransaction entTransaction = entManager.getTrans
entManager.getTransaction();
action();
Note: EntityTransaction
Note: EntityTransaction contains the following methods inorder to complete Transaction.
Note: EntityTranmsaction
Note: EntityTranmsaction is required for only non select operations only, not for select operations.
1. public Object
Object find(Class
find(Class entity_Class,
entity_Class, Serializable
Serializable pk_Value)
pk_Value)
2. public void persist(Object obj)
3. public void remove(Object obj)
Note: To perform Updations , first we have to get Entity object fr om Database table by using find()
Note: To
method then we have to use set New data to Entity Object then perform commit operation.
EX:
1
2
1. EntityTransaction entTranction
entTranction =
= entManager .getTransaction();
.getTransaction(); e
g
a
2. entTransaction.begin(); P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
EX:
Test.java
1. public class
class Test
Test {
2.
3. public static void
void main(String[]
main(String[] args)throws
args)throws Exception
Exception {
4. EntityManagerFactory factory = Persistence.createEntityMan
Persistence.createEntityManagerFactory(
agerFactory("std"
"std");
);
5. EntityManager entManager = factory.createEntityManage
factory.createEntityManager();
r();
6. Student std = new
new Student();
Student();
7. std.setSid("S-111"
std.setSid("S-111");
);
8. std.setSname("AAA"
std.setSname("AAA"); );
9. std.setSaddr("Hyd"
std.setSaddr("Hyd");
);
10. EntityTransaction tx = entManager.getTransaction();
11. tx.begin();
12. entManager.persist(std);
13. tx.commit();
14. System.out.println("Student
System.out.println("Student Inserted Succssfully");
Succssfully");
15. }
16. }
Employee.java
1. package com.durgasoft.pojo;
package com.durgasoft.pojo;
2. public class
class Employee
Employee {
3. private int eno;
int eno;
4. private String
private String ename;
5. private float
float esal;
esal;
6. private String
private String eaddr;
7. public int
int getEno()
getEno() { 2
8. return eno;
return eno; 2
e
9. } g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Employee.xml
1. <?xml version
version=
="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>
?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
5. <hibernate-mapping>
6. <class name
name= ="com.durgasoft.pojo.Employee" table
table=
="emp1"
"emp1">
>
7. <id name
name= ="eno" column
column= ="ENO" />
/>
8. <property name
name= ="ename" column
column= ="ENAME" />
/>
9. <property name
name= ="esal" column
column= ="ESAL" />
/>
10. <property namename= ="eaddr" column
column= ="EADDR" />
/>
11. </class>
12. </hibernate-mapping>
src/META-INF/persistence.xml
3
1. <?xml version
version=
="1.0" encoding
encoding=="UTF-8"
"UTF-8"?>
?> 2
e
2. <persistence xmlns:xsi
xmlns:xsi=
="http://www.w3.org/2001/XMLSchema-instance" g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Test.java
1. package
package com.durgasoft.test;
com.durgasoft.test;
2.
3. import
import javax.persistence.EntityManager;
javax.persistence.EntityManager;
4. import javax.persistence.EntityM
javax.persistence.EntityManagerFactory;
anagerFactory;
5. import javax.persistence.EntityTra
javax.persistence.EntityTransaction;
nsaction;
6. import javax.persistence.Persis
javax.persistence.Persistence;
tence;
7.
8. import
import com.durgasoft.pojo.Employee;
com.durgasoft.pojo.Employee;
9.
10. public class
class Test
Test {
11.
12. public static void
void main(String[]
main(String[] args)throws
args)throws Exception
Exception {
13. EntityManagerFactory factory = Persistence.createEntityMan
Persistence.createEntityManagerFactory(
agerFactory("emp"
"emp");
);
14. EntityManager entManager = factory.createEntityManage
factory.createEntityManager();
r();
15. Employee emp = new new Employee();
Employee();
16. emp.setEno(111
emp.setEno(111); );
17. emp.setEname("AAA"
emp.setEname("AAA"); );
18. emp.setEsal(5000
emp.setEsal(5000); );
4
19. emp.setEaddr("Hyd"
emp.setEaddr("Hyd"); ); 2
20. EntityTransaction tx = entManager.getTransaction(); e
g
a
21. tx.begin(); P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
If we want to use Annotations in JPA application then we have to use the following steps.
1. <persistence>
2. <persistence-unit name
name= ="std"
"std">
>
3. <class>com.durgasoft.entity.Student
<class> com.durgasoft.entity.Student</class>
</class>
4. ------
5. </persistence-unit>
6. </persistence>
Example:
Employee.java
1. package
package com.durgasoft.pojo;
com.durgasoft.pojo;
2.
3. import
import javax.persistence.Column;
javax.persistence.Column;
4. import
import javax.persistence.Entity;
javax.persistence.Entity;
5. import
import javax.persistence.Id;
javax.persistence.Id;
6. import
import javax.persistence.Table;
javax.persistence.Table;
7.
8. @Entity
9. @Table
@Table(name=
(name="emp2"
"emp2"))
10. public class
class Employee
Employee {
11. @Id 5
12. @Column
@Column(name=
(name="ENO"
"ENO")) 2
e
13. private int int eno;
eno; g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
src/META-INF/persistence.xml
1. <?xml version
version=="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>
?>
2. <persistence xmlns:xsi
xmlns:xsi=
="http://www.w3.org/2001/XMLSchema-instance"
3. xsi:schemaLocation=
xsi:schemaLocation ="http://java.sun.com/xml/ns/persistenc
"http://java.sun.com/xml/ns/persistence
e http://java.sun.com/xml/ns/p
ersistence/persistence_2_0.xsd"
6
4. version=
version ="2.0" xmlns
xmlns=="http://java.sun.com/xml/ns/persistence"
"http://java.sun.com/xml/ns/persistence">
> 2
5. <persistence-unit name
name=="emp"
"emp"> > e
g
a
6. <class> com.durgasoft.pojo.Employee</class>
<class>com.durgasoft.pojo.Employee </class> P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Test.java
1. package
package com.durgasoft.test;
com.durgasoft.test;
2.
3. import
import javax.persistence.EntityManager;
javax.persistence.EntityManager;
4. import javax.persistence.EntityM
javax.persistence.EntityManagerFactory;
anagerFactory;
5. import javax.persistence.EntityTra
javax.persistence.EntityTransaction;
nsaction;
6. import javax.persistence.Persis
javax.persistence.Persistence;
tence;
7.
8. import
import com.durgasoft.pojo.Employee;
com.durgasoft.pojo.Employee;
9.
10. public class Test {
class Test
11.
12. public static void
void main(String[]
main(String[] args)throws
args)throws Exception
Exception {
13. EntityManagerFactory factory = Persistence.createEntityMan
Persistence.createEntityManagerFactory(
agerFactory("emp"
"emp");
);
14. EntityManager entManager = factory.createEntityManage
factory.createEntityManager();
r();
15. Employee emp = new new Employee();
Employee();
16. emp.setEno(111
emp.setEno(111); );
17. emp.setEname("AAA"
emp.setEname("AAA"); );
18. emp.setEsal(5000
emp.setEsal(5000); );
19. emp.setEaddr("Hyd"
emp.setEaddr("Hyd"); );
20. EntityTransaction tx = entManager.getTransaction();
21. tx.begin();
22. entManager.persist(emp);
23. tx.commit();
7
24. System.out.println("Employee
System.out.println("Employee Inserted Succssfully"
Succssfully");
); 2
25. } e
g
a
26. } P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
If we want to use JPA with EclipseLink implementation then we have to use the following steps.
1. Create JPA project.
2. Create Entity Class with Annotations
3. Create JPA configuration File
4. Create Test Application
With these steps JPA project will be created in projects Explorer part..
Create package "com.durgasoft.entity" under src folder and create Entity class.
Employee.java
1. package com.durgasoft.entity;
package com.durgasoft.entity;
2. import java.io.Serializable;
import java.io.Serializable;
3. import java.lang.String;
import java.lang.String;
4. import javax.persistence.*;
import javax.persistence.*;
5. @Entity
6. @Table(name=
@Table (name="emp1"
"emp1")) 8
7. public class
class Employee
Employee implements
implements Serializable
Serializable { 2
e
g
8. a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Open persistence.xml file which is existed under"src\META-INF" folder and provide the following
details.
persistence.xml
1. <?xml version
version=="1.0" encoding
encoding=="UTF-8"
"UTF-8"?>?>
2. <persistence version
version=
="2.1" xmlns
xmlns=="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi
xmlns:xsi=
="http
://www.w3.org/2001/XMLSchema-
instance" xsi:schemaLocation
xsi:schemaLocation= ="http://xmlns.jcp.org/xml/ns/persistenc
"http://xmlns.jcp.org/xml/ns/persistence e http://xmlns.jcp.org/x
ml/ns/persistence/persistence_2_1.xsd">
ml/ns/persistence/persistence_2_1.xsd" >
3. <persistence-unit name
name=="emp"
"emp"> >
4. <class>
<class>com.durgasoft.entity.Employee
com.durgasoft.entity.Employee</class>
</class>
5. <properties>
6. <property name
name= ="javax.persistence.jdbc.driver" value
value=="oracle.jdbc.OracleDriver" /> />
7. <property name
name= ="javax.persistence.jdbc.url" value
value=="jdbc:oracle:thin:@localhost:1521:xe" / /
>
8. <property name
name= ="javax.persistence.jdbc.user" value
value=="system" />
/>
9. <property name
name= ="javax.persistence.jdbc.password" value
value=
="durga" />
/>
10. </properties>
11. </persistence-unit>
12. </persistence>
1. package
package com.durgasoft.test;
com.durgasoft.test;
2.
3. import
import javax.persistence.EntityManager;
javax.persistence.EntityManager;
4. import javax.persistence.EntityM
javax.persistence.EntityManagerFactory;
anagerFactory;
5. import javax.persistence.EntityTra
javax.persistence.EntityTransaction;
nsaction;
6. import javax.persistence.Persis
javax.persistence.Persistence;
tence;
7.
8. import
import com.durgasoft.entity.Employee;
com.durgasoft.entity.Employee;
9. 0
10. public class
class Test
Test { 3
e
11. g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
1. Create Java Project with both Spring Library and Hibernate Library.
2. Create Dao interface
3. Create Dao implementation classs.
4. Create POJO / Entity
Entity class.
5. Create Hibernate Mapping File.
6. Create Spring Configuration File.
7. Create Test Application.
Spring Library:
commons-logging-1.2.jar
spring-aop-4.3.9.RELEASE.jar
spring-beans-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-context-support-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar
spring-jdbc-4.3.9.RELEASE.jar
spring-orm-4.3.9.RELEASE.jar
spring-tx-4.3.9.RELEASE.jar
Hibernate Library:
hibernate3.jar
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
ojdbc6.jar
2
3
e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
EmployeeDao.java
1. package
package com.durgasoft.dao;
com.durgasoft.dao;
2.
3. import
import com.durgasoft.entity.Employee;
com.durgasoft.entity.Employee;
4.
5. public interface EmployeeDao {
interface EmployeeDao
6. public String
public String insertEmployee(Employee emp);
7. public Employee
public Employee findEmployee(int
findEmployee(int eno);
eno);
8. public String
public String updateEmployee(Emplo
updateEmployee(Employeeyee emp);
9. public String
public String removeEmployee(int
removeEmployee(int eno);
eno);
10. }
1. package
package com.durgasoft.dao;
com.durgasoft.dao;
2.
3. import
import javax.persistence.EntityManager;
javax.persistence.EntityManager;
4. import javax.persistence.Persis
javax.persistence.PersistenceContext;
tenceContext;
5.
6. import org.springframework.stereotype.R
org.springframework.stereotype.Repository;
epository;
7. import org.springframework.transaction.an
org.springframework.transaction.annotation.Transactional;
notation.Transactional;
8.
9. import
import com.durgasoft.entity.Employee;
com.durgasoft.entity.Employee;
10.
11. @Repository
12. public class
class EmployeeDaoImpl
EmployeeDaoImpl implements
implements EmployeeDao
EmployeeDao {
13.
14. String status = "" "";;
15.
16. @PersistenceContext
17. private
private EntityManager
EntityManager entityManager;
18.
19. @Transactional
20. @Override
21. public
public String
String insertEmployee(Employee emp) {
22. entityManager.persist(emp); 3
23. status = "SUCCESS"
"SUCCESS";; 3
e
24. return status;
return status; g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Where "@PersistenceContext"
"@PersistenceContext" will inject EntityManager
EntityManager object into Dao implementation
class.
Where "@Transactional"
"@Transactional" annotation will inject Transaction
Transaction service in DAO methiods,
methiods, where
it is not required to Create EntityTransaction object and not required to perform commit() or
rollback() operations.
Employee.java
4
3
1. package
package com.durgasoft.entity;
com.durgasoft.entity; e
g
a
2. P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Employee.xml
1. <?xml version
version=
="1.0" encoding
encoding=
="UTF-8"
"UTF-8"?>
?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
5
5. <hibernate-mapping> 3
6. <class name
name=="com.durgasoft.entity.Employee" table
table=
="emp1"
"emp1">
> e
g
a
7. <id name
name=="eno" />
/> P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
applicationContext.xml
1. <?xml version
version= ="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>
?>
2. <beans xmlns
xmlns= ="http://www.springframework.org/schema/beans"
3. xmlns:xsi=
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:aop=
xmlns:aop ="http://www.springframework.org/schema/aop"
5. xmlns:tx=
xmlns:tx ="http://www.springframework.org/schema/tx"
6. xmlns:context=
xmlns:context ="http://www.springframework.org/schema/context"
7.
8. xsi:schemaLocation="
xsi:schemaLocation ="
9. http://www.springframework.org/schema/beans
10. http://www.springframework.org/schema/beans/spring-beans.xsd
11. http://www.springframework.org/schema/tx
12. http://www.springframework.org/schema/tx/spring-tx.xsd
13. http://www.springframework.org/schema/aop
14. http://www.springframework.org/schema/aop/spring-aop.xsd
15. http://www.springframework.org/schema/context
16. http://www.springframework.org/schema/context/spring-context.xsd">
http://www.springframework.org/schema/context/spring-context.xsd" >
17. <context:annotation-config/>
18. <tx:annotation-driven/>
19. <bean idid=
="dataSource" class class=="org.springframework.jdbc.datasource.DriverManagerData
Source">
Source" >
20. <property name
name= ="driverClassName" value
value=="oracle.jdbc.OracleDriver" />
/>
21. <property name
name= ="url" value
value=
="jdbc:oracle:thin:@localhost:1521:xe" />
/>
22. <property name
name= ="username" value
value=="system" />
/>
23. <property name
name= ="password" value
value=="durga" />
/>
24. </bean>
25. <bean idid=
="entityManagerFactoryBean" class class=
="org.springframework.orm.jpa.LocalContaine
rEntityManagerFactoryBean">
rEntityManagerFactoryBean" >
26. <property name name= ="dataSource" ref ="dataSource" /> />
27. <property name name= ="persistenceUnitName" valuevalue=
="emp" />
/>
28. <property name name= ="jpaVendorAdapter"
"jpaVendorAdapter"> >
6
29. <bean class
class=="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> /> 3
30. </property> e
g
a
31. <property name name= ="mappingResources"
"mappingResources"> > P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Where "org.springframework.jdbc.datasou
"org.springframework.jdbc.datasource.DriverManagerDataSo
rce.DriverManagerDataSource"
urce" will provide
dataSource object, it required the following
f ollowing dependencies.
1. driverClassName
2. url
3. username
4. password
Where "org.springframework.orm.jpa.LocalCo
"org.springframework.orm.jpa.LocalContainerEntityManagerFac
ntainerEntityManagerFactoryBean"
toryBean" will
provide EntityManager object in Spring Application and it require the following
dependencies.
1. dataSource
2. persistenceUnitName
3. jpaVendorAdapter
4. mappingResources
5. jpaProperties
Where "dataSource"
"dataSource" will take a DataSource reference which
which we configure in Spring
Spring
configuration File.
Where "persistenceUnitName"
"persistenceUnitName" will
will take persistence name
name like "emp".
7
Where "jpaVendorAdpter"property
"jpaVendorAdpter"property will take the class like 3
"org.springframework.orm.jpa.vendor.HibernateJpaVend
"org.springframework.orm.jpa.vendo r.HibernateJpaVendorAdapter"
orAdapter" and it will provide all e
g
a
Hibernate implementation of JPA to Spring application. P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Where "mappingResources"
"mappingResources" property will take all mapping
mapping Files which we are using in
spring applications in the form of <list> type.
Where "jpaProperties"
"jpaProperties" will take JPA implementation properties like dialect, show_sql,... in
the form of "<props>" type.
Where "org.springframework.orm.jpa.JpaTransac
"org.springframework.orm.jpa.JpaTransactionManager"
tionManager" will provide Transaction
implementation provided by JPA vendor.
Where "<context:annotation-config/>"
"<context:annotation-config/>" tag will activate the annotations
annotations like "@Repository"
, "@Service", "@Component".......
Where "<tx:annotation-driven/>"
"<tx:annotation-driven/>" tag will activate @Transactional
@Transactional annotation which will
inject Transaction Service in Spring application.
1. package
package com.durgasoft.test;
com.durgasoft.test;
2.
3. import org.springframework.contex
org.springframework.context.ApplicationContext;
t.ApplicationContext;
4. import org.springframework.contex
org.springframework.context.support.ClassPathXmlApplicationCo
t.support.ClassPathXmlApplicationContext;
ntext;
5. import org.springframework.orm.jpa.vend
org.springframework.orm.jpa.vendor.HibernateJpaVendo
or.HibernateJpaVendorAdapter;
rAdapter;
6.
7. import com.durgasoft.dao.Emplo
com.durgasoft.dao.EmployeeDao;
yeeDao;
8. import
import com.durgasoft.entity.Employee;
com.durgasoft.entity.Employee;
9.
10. public class
class Test
Test {
11.
12. public static voidvoid main(String[]
main(String[] args) {
13. ApplicationContext
ApplicationContext context = new ClassPathXmlApplica
ClassPathXmlApplicationContext(
tionContext("applicationConte
"applicationConte
xt.xml");
xt.xml" );
14. EmployeeDao empDao = (EmployeeDao) context.getBean("empDao"
context.getBean("empDao"); );
15. /*
16. Employee emp = new Employee();
17. emp.setEno(111);
18. emp.setEname("AAA");
19. emp.setEsal(5000);
20. emp.setEaddr("Hyd");
21. String status = empDao.insertEmploy
empDao.insertEmployee(emp);
ee(emp);
8
22. System.out.println(status); 3
23. */ e
g
a
24. /* P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Example:
Employee.java
1. package
package com.durgasoft.pojo;
com.durgasoft.pojo;
2.
3. public class
class Employee
Employee {
4. private int
int eno;
eno;
5. private String
private String ename;
6. private float
float esal;
esal;
7. private String
private String eaddr;
8.
9. public int
int getEno()
getEno() {
10. return eno;
return eno;
11. }
12. public void
void setEno(
setEno(int
int eno)
eno) {
13. this.eno
this.eno = eno;
9
14. } 3
15. public
public String
String getEname() { e
g
a
16. ename;
return ename;
return P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
EmployeeDao.java
1. package
package com.durgasoft.dao;
com.durgasoft.dao;
2.
3. import
import com.durgasoft.entity.Employee;
com.durgasoft.entity.Employee;
4.
5. public interface
interface EmployeeDao
EmployeeDao {
6. public String
public String insertEmployee(Employee emp);
7. public Employee
public Employee findEmployee(int
findEmployee(int eno);
eno);
8. public String
public String updateEmployee(Emplo
updateEmployee(Employeeyee emp);
9. public String
public String removeEmployee(int
removeEmployee(int eno);
eno);
10. }
EmployeeDaoImpl.java
1. package
package com.durgasoft.dao;
com.durgasoft.dao;
2.
0
3. import
import javax.persistence.EntityManager;
javax.persistence.EntityManager; 4
e
4. import javax.persistence.Persis
javax.persistence.PersistenceContext;
tenceContext; g
a
5. P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Employee.hbm.xml
1. <?xml version
version=
="1.0" encoding
encoding=="UTF-8"
"UTF-8"?>?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
5. <hibernate-mapping>
6. <class name
name=="com.durgasoft.pojo.Employee" table
table=
="emp2"
"emp2">
>
7. <id name
name=="eno" column
column=="ENO" />
/>
8. <property name
name=="ename" column
column= ="ENAME" />
/>
9. <property name
name=="esal" column
column= ="ESAL" />
/>
10. <property name
name=="eaddr" column
column= ="EADDR" />
11. </class>
12. </hibernate-mapping>
applicationContext.xml
1. <?xml version
version= ="1.0" encoding
encoding=="UTF-8"
"UTF-8"?>
?>
2. <beans xmlns
xmlns=="http://www.springframework.org/schema/beans"
3. xmlns:xsi=
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:aop=
xmlns:aop ="http://www.springframework.org/schema/aop"
5. xmlns:tx=
xmlns:tx ="http://www.springframework.org/schema/tx"
6. xmlns:context=
xmlns:context ="http://www.springframework.org/schema/context"
7.
8. xsi:schemaLocation="
xsi:schemaLocation ="
9. http://www.springframework.org/schema/beans
10. http://www.springframework.org/schema/beans/spring-beans.xsd
11. http://www.springframework.org/schema/tx
12. http://www.springframework.org/schema/tx/spring-tx.xsd
13. http://www.springframework.org/schema/aop
14. http://www.springframework.org/schema/aop/spring-aop.xsd
15. http://www.springframework.org/schema/context
16. http://www.springframework.org/schema/context/spring-context.xsd">
http://www.springframework.org/schema/context/spring-context.xsd">
2
17. <context:annotation-config/> 4
e
18. <tx:annotation-driven/> g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
Test.java
1. package com.durgasoft.test;
package com.durgasoft.test;
2.
3. import org.springframework.contex
org.springframework.context.ApplicationContext;
t.ApplicationContext;
4. import org.springframework.context.supp
org.springframework.context.support.ClassPathXmlApplicati
ort.ClassPathXmlApplicationContext;
onContext;
5. import org.springframework.orm.jpa.vend
org.springframework.orm.jpa.vendor.HibernateJpaVendo
or.HibernateJpaVendorAdapter;
rAdapter;
3
6. 4
7. import com.durgasoft.dao.Emplo
com.durgasoft.dao.EmployeeDao;
yeeDao; e
g
a
8. com.durgasoft.entity.Employee;
import com.durgasoft.entity.Employee;
import P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: [email protected]