Spring ORM Course Materials by Nagoor Babu
Spring ORM Course Materials by 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: durgasoftonlinetraining@[Link]
2
e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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: durgasoftonlinetraining@[Link]
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. [Link]("[Link]"); 4
e
g
3. SessionFactory session_Factory
session_Factory =
= cfg
[Link]();
.buildSessionFactory(); a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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 "[Link]"
package.
Note: If
Note: If we use Hibernate3.x version then we have to use
"[Link]"
"[Link].hibernate3 .HibernateTemplate" class.
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Hibernate4_Lib:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
jboss-logging-annotation [Link]
jboss-transaction-api_1.2_spec-[Link]
jboss-transaction-api_1.2_s [Link]
[Link]
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: durgasoftonlinetraining@[Link]
[Link]
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. [Link]
[Link] = hibernateTemplate; P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
Where [Link]
[Link]
[Link]
ataSource configuration is
able to provide Spring inbuilt Connectionpooling
Connectionpooling Mechanism and it will include the
properties liike "driverClassName, url, username, password".
Where [Link]
[Link]
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 "[Link]" property.
Where [Link].hibernate4
[Link]
.HibernateTransactionManager
nager configuration
will activate Transaction Manager inorder to provide Tr ansaction Support and it will include
"sessionFactory" property.
Where [Link]
[Link]
ateTemplate configuration will provide
HibernateTemplate object inorder to perform persistence operations and it will include
"sessionFactory" and "checkWriteOperations" with false value.
Where [Link]
[Link] 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: durgasoftonlinetraining@[Link]
[Link]
1. <?xml version
version= ="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>?>
2. <beans xmlns
xmlns= ="[Link]
3. xmlns:xsi=
xmlns:xsi ="[Link]
4. xmlns:aop=
xmlns:aop ="[Link]
5. xmlns:tx=
xmlns:tx ="[Link]
6. xsi:schemaLocation="
xsi:schemaLocation ="
7. [Link]
8. [Link]
9. [Link]
10. [Link]
11. [Link]
12. [Link]
[Link] >
13.
14. <bean name
name= ="dataSource" class
class=="[Link]
ataSource">
ataSource" >
15. <property name name= ="driverClassName" value
value=
="[Link]" />
/>
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=
="[Link]
actoryBean">
actoryBean" >
21. <property name name= ="dataSource" ref ="dataSource" /> />
22. <property name name= ="mappingResources"
"mappingResources"> >
23. <list>
24. <value>[Link]
<value> [Link]</value>
</value>
25. </list>
26. </property>
27. <property name name= ="hibernateProperties"
"hibernateProperties"> >
28. <props>
29. <prop keykey=="[Link]"
"[Link]">>[Link].Oracle10gDialect
[Link].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=="[Link] 1
nsactionManager">
nsactionManager" > e
g
a
36. <property name
name= ="sessionFactory" ref ="sessionFactory" />
/> P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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("[Link]
[Link]
");
2. StudentDao stdDao
stdDao = = (StudentDao)[Link]("stdDao");
(StudentDao)[Link]("stdDao");
3. Student std
std =
= new
new Student();
Student();
4. [Link]("S-111");
5. [Link]("AAA");
6. [Link]("Hyd");
7. String status
status =
= stdDao
[Link](std);
.insert(std);
8. [Link](status);
9. or
10. Student std
std =
= (Student)[Link]
(Student)[Link]([Link],"S-111");
ent([Link],"S-111");
11. [Link]("Student Details");
12. [Link]("--------------------");
13. [Link]("Student Id :"+[Link]());
14. [Link]("Student Name :"+[Link]());
15. [Link]("Student Address :"+[Link]());
16. or
17. Student std
std =
= new
new Student();
Student();
18. [Link]("S-111");
19. [Link]("BBB");
20. [Link]("Hyd");
21. String status
status =
= stdDao
[Link](std);
.update(std);
22. [Link](status);
1
23. or 1
24. String status
status =
= stdDao
[Link]("S-111");
.delete("S-111"); e
g
a
25. [Link](status); P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
[Link]
1. package
package [Link];
[Link];
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. [Link]
[Link] = eno;
14. }
15. public String getEname() {
public String
16. return ename;
return ename;
17. }
18. public void
void setEname(String
setEname(String ename) {
19. [Link]
[Link] = 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. [Link]
[Link] = esal;
26. }
27. public
public String
String getEaddr() {
28. return eaddr;
return eaddr;
29. }
30. public void
void setEaddr(String
setEaddr(String eaddr) {
31. [Link]
[Link] = 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: durgasoftonlinetraining@[Link]
[Link]
1. package
package [Link];
[Link];
2.
3. import
import [Link];
[Link];
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. }
[Link]
1. package
package [Link];
[Link];
2. import
import [Link];
[Link];
3. import
import [Link];
[Link];
4. import [Link].hibernate4.
[Link];
HibernateTemplate;
5. import [Link]
[Link];
[Link];
6.
7. import
import [Link];
[Link];
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. [Link]
this .hibernateTemplate = hibernateTemplate;
14.
15. }
16.
17. @Override
18. @Transactional
19. public
public String
String insert(Employee e) {
20. try {
try {
21. [Link](e);
22. status = "Insertion Success";
Success";
3
23. }catch
catch(Exception
(Exception ex) { 1
e
24. [Link](); g
a
25. status = "Insertion Failure";
Failure"; P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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. "[Link]
"[Link]
5. <hibernate-mapping>
6. <class name
name=="[Link]" 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>
[Link]
1. <?xml version
version=="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>?>
2. <beans xmlns
xmlns=="[Link]
3. xmlns:xsi=
xmlns:xsi ="[Link]
4. xmlns:aop=
xmlns:aop ="[Link]
5. xmlns:tx=
xmlns:tx ="[Link]
6. xsi:schemaLocation="
xsi:schemaLocation ="
7. [Link]
8. [Link]
9. [Link]
10. [Link]
11. [Link]
12. [Link]
[Link] >
13.
14.
15. <bean name
name= ="dataSource" class
class=="[Link]
ataSource">
ataSource" >
16. <property name name= ="driverClassName" value
value=="[Link]" />
/>
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=
="[Link]
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: durgasoftonlinetraining@[Link]
[Link]
1. package
package [Link];
[Link];
2.
3. import [Link]
[Link];
[Link];
4. import [Link]
[Link]
[Link];
tionContext;
5. import [Link].hibernate4.
[Link];
HibernateTemplate;
6.
7. import [Link]
[Link];
yeeDao;
8. import
import [Link];
[Link];
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
[Link]");
[Link]"); P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
7
1
e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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[[Link]]
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.
[Link]
8
1. package [Link];
package [Link]; 1
e
g
2. public class
class Student{
Student{ a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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:
[Link]
1. <hibernate-mapping>
2. <class name
name=="[Link]" 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 [Link]: 9
1
e
1. <persistence> g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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: durgasoftonlinetraining@[Link]
EX: EntityManager
EX: EntityManager entManager = [Link]
f [Link]();
er();
EX: EntityTransaction
EX: EntityTransaction entTransaction = [Link]
[Link]();
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. [Link](); P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
EX:
[Link]
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 = [Link]
[Link](
agerFactory("std"
"std");
);
5. EntityManager entManager = [Link]
[Link]();
r();
6. Student std = new
new Student();
Student();
7. [Link]("S-111"
[Link]("S-111");
);
8. [Link]("AAA"
[Link]("AAA"); );
9. [Link]("Hyd"
[Link]("Hyd");
);
10. EntityTransaction tx = [Link]();
11. [Link]();
12. [Link](std);
13. [Link]();
14. [Link]("Student
[Link]("Student Inserted Succssfully");
Succssfully");
15. }
16. }
[Link]
1. package [Link];
package [Link];
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: durgasoftonlinetraining@[Link]
[Link]
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. "[Link]
"[Link] >
5. <hibernate-mapping>
6. <class name
name= ="[Link]" 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/[Link]
3
1. <?xml version
version=
="1.0" encoding
encoding=="UTF-8"
"UTF-8"?>
?> 2
e
2. <persistence xmlns:xsi
xmlns:xsi=
="[Link] g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
[Link]
1. package
package [Link];
[Link];
2.
3. import
import [Link];
[Link];
4. import [Link]
[Link];
anagerFactory;
5. import [Link]
[Link];
nsaction;
6. import [Link]
[Link];
tence;
7.
8. import
import [Link];
[Link];
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 = [Link]
[Link](
agerFactory("emp"
"emp");
);
14. EntityManager entManager = [Link]
[Link]();
r();
15. Employee emp = new new Employee();
Employee();
16. [Link](111
[Link](111); );
17. [Link]("AAA"
[Link]("AAA"); );
18. [Link](5000
[Link](5000); );
4
19. [Link]("Hyd"
[Link]("Hyd"); ); 2
20. EntityTransaction tx = [Link](); e
g
a
21. [Link](); P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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>[Link]
<class> [Link]</class>
</class>
4. ------
5. </persistence-unit>
6. </persistence>
Example:
[Link]
1. package
package [Link];
[Link];
2.
3. import
import [Link];
[Link];
4. import
import [Link];
[Link];
5. import
import [Link];
[Link];
6. import
import [Link];
[Link];
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: durgasoftonlinetraining@[Link]
src/META-INF/[Link]
1. <?xml version
version=="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>
?>
2. <persistence xmlns:xsi
xmlns:xsi=
="[Link]
3. xsi:schemaLocation=
xsi:schemaLocation ="[Link]
"[Link]
e [Link]
ersistence/persistence_2_0.xsd"
6
4. version=
version ="2.0" xmlns
xmlns=="[Link]
"[Link]
> 2
5. <persistence-unit name
name=="emp"
"emp"> > e
g
a
6. <class> [Link]</class>
<class>[Link] </class> P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
[Link]
1. package
package [Link];
[Link];
2.
3. import
import [Link];
[Link];
4. import [Link]
[Link];
anagerFactory;
5. import [Link]
[Link];
nsaction;
6. import [Link]
[Link];
tence;
7.
8. import
import [Link];
[Link];
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 = [Link]
[Link](
agerFactory("emp"
"emp");
);
14. EntityManager entManager = [Link]
[Link]();
r();
15. Employee emp = new new Employee();
Employee();
16. [Link](111
[Link](111); );
17. [Link]("AAA"
[Link]("AAA"); );
18. [Link](5000
[Link](5000); );
19. [Link]("Hyd"
[Link]("Hyd"); );
20. EntityTransaction tx = [Link]();
21. [Link]();
22. [Link](emp);
23. [Link]();
7
24. [Link]("Employee
[Link]("Employee Inserted Succssfully"
Succssfully");
); 2
25. } e
g
a
26. } P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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 "[Link]" under src folder and create Entity class.
[Link]
1. package [Link];
package [Link];
2. import [Link];
import [Link];
3. import [Link];
import [Link];
4. import [Link].*;
import [Link].*;
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: durgasoftonlinetraining@[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
Open [Link] file which is existed under"src\META-INF" folder and provide the following
details.
[Link]
1. <?xml version
version=="1.0" encoding
encoding=="UTF-8"
"UTF-8"?>?>
2. <persistence version
version=
="2.1" xmlns
xmlns=="[Link] xmlns:xsi
xmlns:xsi=
="http
://[Link]/2001/XMLSchema-
instance" xsi:schemaLocation
xsi:schemaLocation= ="[Link]
"[Link] e [Link]
ml/ns/persistence/persistence_2_1.xsd">
ml/ns/persistence/persistence_2_1.xsd" >
3. <persistence-unit name
name=="emp"
"emp"> >
4. <class>
<class>[Link]
[Link]</class>
</class>
5. <properties>
6. <property name
name= ="[Link]" value
value=="[Link]" /> />
7. <property name
name= ="[Link]" value
value=="jdbc:oracle:thin:@localhost:1521:xe" / /
>
8. <property name
name= ="[Link]" value
value=="system" />
/>
9. <property name
name= ="[Link]" value
value=
="durga" />
/>
10. </properties>
11. </persistence-unit>
12. </persistence>
1. package
package [Link];
[Link];
2.
3. import
import [Link];
[Link];
4. import [Link]
[Link];
anagerFactory;
5. import [Link]
[Link];
nsaction;
6. import [Link]
[Link];
tence;
7.
8. import
import [Link];
[Link];
9. 0
10. public class
class Test
Test { 3
e
11. g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
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:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Hibernate Library:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
2
3
e
g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
[Link]
1. package
package [Link];
[Link];
2.
3. import
import [Link];
[Link];
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 [Link];
[Link];
2.
3. import
import [Link];
[Link];
4. import [Link]
[Link];
tenceContext;
5.
6. import [Link].R
[Link];
epository;
7. import [Link]
[Link];
[Link];
8.
9. import
import [Link];
[Link];
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. [Link](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: durgasoftonlinetraining@[Link]
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.
[Link]
4
3
1. package
package [Link];
[Link]; e
g
a
2. P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
[Link]
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. "[Link]
"[Link]
5
5. <hibernate-mapping> 3
6. <class name
name=="[Link]" table
table=
="emp1"
"emp1">
> e
g
a
7. <id name
name=="eno" />
/> P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
[Link]
1. <?xml version
version= ="1.0" encoding
encoding= ="UTF-8"
"UTF-8"?>
?>
2. <beans xmlns
xmlns= ="[Link]
3. xmlns:xsi=
xmlns:xsi ="[Link]
4. xmlns:aop=
xmlns:aop ="[Link]
5. xmlns:tx=
xmlns:tx ="[Link]
6. xmlns:context=
xmlns:context ="[Link]
7.
8. xsi:schemaLocation="
xsi:schemaLocation ="
9. [Link]
10. [Link]
11. [Link]
12. [Link]
13. [Link]
14. [Link]
15. [Link]
16. [Link]
[Link] >
17. <context:annotation-config/>
18. <tx:annotation-driven/>
19. <bean idid=
="dataSource" class class=="[Link]
Source">
Source" >
20. <property name
name= ="driverClassName" value
value=="[Link]" />
/>
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=
="[Link]
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=="[Link]" /> /> 3
30. </property> e
g
a
31. <property name name= ="mappingResources"
"mappingResources"> > P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
Where "[Link]
"[Link]
[Link]"
urce" will provide
dataSource object, it required the following
f ollowing dependencies.
1. driverClassName
2. url
3. username
4. password
Where "[Link]
"[Link]
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
"[Link]
"[Link] [Link]"
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: durgasoftonlinetraining@[Link]
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 "[Link]
"[Link]"
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 [Link];
[Link];
2.
3. import [Link]
[Link];
[Link];
4. import [Link]
[Link]
[Link];
ntext;
5. import [Link]
[Link]
[Link];
rAdapter;
6.
7. import [Link]
[Link];
yeeDao;
8. import
import [Link];
[Link];
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
[Link]");
[Link]" );
14. EmployeeDao empDao = (EmployeeDao) [Link]("empDao"
[Link]("empDao"); );
15. /*
16. Employee emp = new Employee();
17. [Link](111);
18. [Link]("AAA");
19. [Link](5000);
20. [Link]("Hyd");
21. String status = [Link]
[Link](emp);
ee(emp);
8
22. [Link](status); 3
23. */ e
g
a
24. /* P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
Example:
[Link]
1. package
package [Link];
[Link];
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. [Link]
[Link] = 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: durgasoftonlinetraining@[Link]
[Link]
1. package
package [Link];
[Link];
2.
3. import
import [Link];
[Link];
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. }
[Link]
1. package
package [Link];
[Link];
2.
0
3. import
import [Link];
[Link]; 4
e
4. import [Link]
[Link];
tenceContext; g
a
5. P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
[Link]
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. "[Link]
"[Link]
5. <hibernate-mapping>
6. <class name
name=="[Link]" 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>
[Link]
1. <?xml version
version= ="1.0" encoding
encoding=="UTF-8"
"UTF-8"?>
?>
2. <beans xmlns
xmlns=="[Link]
3. xmlns:xsi=
xmlns:xsi ="[Link]
4. xmlns:aop=
xmlns:aop ="[Link]
5. xmlns:tx=
xmlns:tx ="[Link]
6. xmlns:context=
xmlns:context ="[Link]
7.
8. xsi:schemaLocation="
xsi:schemaLocation ="
9. [Link]
10. [Link]
11. [Link]
12. [Link]
13. [Link]
14. [Link]
15. [Link]
16. [Link]
[Link]
2
17. <context:annotation-config/> 4
e
18. <tx:annotation-driven/> g
a
P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
[Link]
1. package [Link];
package [Link];
2.
3. import [Link]
[Link];
[Link];
4. import [Link]
[Link]
[Link];
onContext;
5. import [Link]
[Link]
[Link];
rAdapter;
3
6. 4
7. import [Link]
[Link];
yeeDao; e
g
a
8. [Link];
import [Link];
import P
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@[Link]
The 'removeEmployee' method utilizes transaction management through the '@Transactional' annotation, ensuring that the deletion of a record is atomic. This means that if any part of the transaction fails, the operation will be rolled back automatically, preventing partial changes and thus maintaining database integrity. This method minimizes risks of having orphaned or inconsistent data entries due to operation failures or errors during the delete operation .
The 'Employee' POJO supports data encapsulation by using private fields (eno, ename, esal, eaddr) to store data and providing public getter and setter methods for accessing and modifying these fields. This is an important principle in software design because it protects the integrity of the data by restricting direct access and modifications. Furthermore, it allows for controlled access by providing a structure for validation and logging, and it enhances maintainability by isolating changes in implementation from other parts of the application .
The '@PersistenceContext' annotation is used in the EmployeeDaoImpl class to inject an instance of EntityManager, which is crucial for managing entity objects in JPA. The primary advantage is that it handles the lifecycle of entities transparently, enabling operations like creating, reading, updating, and deleting entities with ease. It eliminates the need for manual EntityManager instantiation and thus leads to cleaner code with reduced boilerplate. Furthermore, it supports transaction management automatically when coupled with '@Transactional', ensuring data integrity .
The 'updateEmployee' method in the EmployeeDaoImpl class uses the '@Transactional' annotation to manage transactions automatically. This annotation allows the method to perform database operations without manually handling transaction creation and commit/rollback operations. The entity manager finds the employee by ID, updates the employee's details, and sets the status to 'SUCCESS'. The significance of using '@Transactional' is that it provides atomicity and consistency by ensuring that all operations within the method complete successfully or none at all, thus maintaining data integrity in the database .
The Hibernate mapping file 'Employee.hbm.xml' maps the 'Employee' class fields to the database columns by specifying a <class> element that maps to the 'emp1' table in the database. Inside this element, the <id> and <property> elements map the fields of the Employee class (eno, ename, esal, eaddr) to their respective columns (ENO, ENAME, ESAL, EADDR). Each mapping specifies the property name and the corresponding column name, facilitating the translation between the class and the database structure .
Configuring a HibernateTemplate bean in a Spring application simplifies database operations by providing a wrapper around Hibernate's native Session API. It simplifies error handling by converting Hibernate exceptions to unchecked DataAccessExceptions, which makes exception translation seamless. HibernateTemplate also supports generic data access methods, removing boilerplate code needed for sessions and transactions. Its integration with Spring means it can automatically participate in current transactions configured through Spring's transaction management .
The 'hibernate.show_sql' property, when set to true, logs the SQL statements generated by Hibernate to the console. This aids application development and debugging by allowing developers to see the actual SQL queries executed against the database, which helps in verifying query correctness and diagnosing performance bottlenecks or SQL syntax errors. It provides insights into how Hibernate translates object-interactions into database commands, making it easier to troubleshoot and optimize database interactions .
The 'sessionFactory' bean is critical in integrating Hibernate with Spring as it facilitates the creation of Session instances, which are necessary for interacting with the database. It's configured in the applicationContext.xml by specifying its class as 'org.springframework.orm.hibernate4.LocalSessionFactoryBean'. The dataSource is referenced, mapping resources are specified for entity mappings such as Employee.hbm.xml, and Hibernate properties such as 'hibernate.dialect' and 'hibernate.show_sql' are set to define SQL dialect and display SQL queries, respectively .
Hardcoding database credentials (like username and password) in applicationContext.xml raises security concerns such as unauthorized access and data breaches. These credentials could be exposed if the file is accessed maliciously or improperly managed. To mitigate these risks, credentials can be externalized using environment variables, encrypted properties, or secret management tools (e.g., AWS Secrets Manager). Implementing proper file permissions and securing the configuration file against unauthorized access further enhances security .
The 'org.hibernate.dialect.Oracle10gDialect' property in Hibernate configuration is essential for tailoring SQL syntax generation to match the Oracle 10g database's specific SQL capabilities. This ensures that Hibernate generates queries compatible with the Oracle database, optimizing performance and enabling the leverage of Oracle's database features. This configuration is crucial because using an incorrect dialect can lead to syntax errors or performance issues, which emphasizes its importance for stable and efficient database interactions .









