Wednesday, 29 April 2020

Spring and JPA (Java Persistent API) Integration Application

Spring and JPA (Java Persistent API) Integration Application 



JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise
application. It is currently used as the replacement for complex entity beans. The implementation of JPA specification are provided by many vendors such as:


  • Hibernate
  • Toplink
  • iBatis
  • OpenJPA etc.

Advantage of Spring with JPA

You don't need to write the before and after code for persisting, updating, deleting or searching object such as creating Persistence instance,  creating EntityManagerFactory instance, creating
EntityTransaction instance, creating EntityManager instance,  commiting EntityTransaction instance and closing EntityManager.


Steps:-
Let's see what are the simple steps for Spring 4.0 and JPA integration:

  • First Create a Java Application 
  • create applicationContext.xml file .
  • create User.java file It is the persistent class
  • create UserDao.java file .
  • create SpringHibernateApplication.java  with main method .

For Spring Hibernate application Configuration download jar files by click here 


applicationContext.xml 

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

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:flow="http://www.springframework.org/schema/webflow-config"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:osgi="http://www.springframework.org/schema/osgi"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
          http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
          http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
          http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
          http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
          http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi-1.2.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
          http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
">

<context:annotation-config />
<context:component-scan base-package="in.jk" />
<tx:annotation-driven
transaction-manager="transactionManager" proxy-target-class="true" />

<bean id="postgresDatasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url"
value="jdbc:postgresql://localhost:5432/postgres"></property>
<property name="driverClassName"
value="org.postgresql.Driver"></property>
<property name="username" value="postgres"></property>
<property name="password" value="jk123"></property>
</bean>

<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory" />
</bean>

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="postgresDatasource">

<!-- By Using this no need for classpath:persistance.xml file -->
<property name="packagesToScan" value="in.jk" />
        <property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true"></property>
<property name="databasePlatform"
value="org.hibernate.dialect.PostgreSQLDialect" />
</bean>
</property>
</bean>

     <bean id="userDao" class="in.jk.UserDao">
</bean>


</beans>

User.java

package in.jk;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="user_details")
public class User {
@Id
@Column(name="userId")
private int userId;
@Column(name="name")
private String name;
@Column(name="email")
private String email;
     
      // Getters and Setters
@Override
public String toString() {
return "User [userId=" + userId + ", name=" + name + ", email=" + email + "]";
}
}

UserDao.java

package in.jk;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class UserDao {

@PersistenceContext
EntityManager entityManager;

public void save(User user) {

               entityManager.persist(user);
}

public User get(int id) {

return entityManager.find(User.class, id);
}


}

SpringJpaApplication.java

package in.jk;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringJpaApplication {

public static void main(String[] args) {

ApplicationContext context = null;
EntityManagerFactory entityManagerFactory =null;
context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
entityManagerFactory = (EntityManagerFactory)context.getBean("entityManagerFactory");
                EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();

User user = new User();
user.setUserId(100);
user.setName("JK");
user.setEmail("jk@gmail.com");

// For persist Object
entityManager.persist(user);
System.out.println("User saved in Database ..");

// For find Object
User user1 = entityManager.find(User.class, 100);
System.out.println("User from Database.." + user1);

// For delete Object
entityManager.remove(user1);
System.out.println("User Deleted from Database.." + user1);

entityManager.getTransaction().commit();

                System.out.println();
                System.out.println("Using Second Way :: ");
System.out.println("Persist and find the Object using Dao with Declative Transatcion");

UserDao userDao = (UserDao) context.getBean("userDao");

User userObj = new User();
userObj.setUserId(101);
userObj.setName("JK");
userObj.setEmail("jk@gmail.com");

// For persist Object
userDao.save(userObj);

// For find Object
User userEntity = userDao.get(101);
System.out.println("User from database.." + userEntity);
System.out.println("Completed  Succussfully ....");
}}

Output in Console ....




No comments:

Post a Comment