W3Schools Learner's Blog

W3Schools Programming knowledge summary website

div

12/20/2017

Spring Data JPA Tutorial

Spring Data JPA API provides JpaTemplate class to integrate spring application with JPA.
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 JpaTemplate

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.
So, it save a lot of code.

In this example, we are going to use hibernate for the implementation of JPA.

Example of Spring and JPA Integration

Let's see the simple steps to integration spring application with JPA:
  1. create Account.java file
  2. create Account.xml file
  3. create AccountDao.java file
  4. create persistence.xml file
  5. create applicationContext.xml file
  6. create AccountsClient.java file
In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure of jpa example with spring.
spring jpa example with directory structure

1) Account.java
It is a simple POJO class.
  1. package com.javatpoint;  
  2.   
  3. public class Account {  
  4.     private int accountNumber;  
  5.     private String owner;  
  6.     private double balance;  
  7.         //no-arg and parameterized constructor  
  8.         //getters and setters  
  9. }  

2) Account.xml
This mapping file contains all the information of the persistent class.
  1. <entity-mappings version="1.0"   
  2.         xmlns="http://java.sun.com/xml/ns/persistence/orm"   
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm   
  5.         http://java.sun.com/xml/ns/persistence/orm_1_0.xsd ">  
  6.       
  7.     <entity class="com.javatpoint.Account">  
  8.         <table name="account100"></table>  
  9.         <attributes>  
  10.             <id name="accountNumber">  
  11.                 <column name="accountnumber"/>  
  12.             </id>  
  13.             <basic name="owner">  
  14.                 <column name="owner"/>  
  15.             </basic>  
  16.             <basic name="balance">  
  17.                 <column name="balance"/>  
  18.             </basic>  
  19.         </attributes>  
  20.     </entity>  
  21. </entity-mappings>  


3) AccountDao.java
  1. package com.javatpoint;  
  2. import java.util.List;  
  3. import org.springframework.orm.jpa.JpaTemplate;  
  4. import org.springframework.transaction.annotation.Transactional;  
  5. @Transactional  
  6. public class AccountsDao{  
  7.     JpaTemplate template;  
  8.   
  9.     public void setTemplate(JpaTemplate template) {  
  10.         this.template = template;  
  11.     }  
  12.     public void createAccount(int accountNumber,String owner,double balance){  
  13.         Account account = new Account(accountNumber,owner,balance);  
  14.         template.persist(account);  
  15.     }  
  16.     public void updateBalance(int accountNumber,double newBalance){  
  17.         Account account = template.find(Account.class, accountNumber);  
  18.         if(account != null){  
  19.             account.setBalance(newBalance);  
  20.         }  
  21.         template.merge(account);  
  22.     }  
  23.     public void deleteAccount(int accountNumber){  
  24.         Account account = template.find(Account.class, accountNumber);  
  25.         if(account != null)  
  26.             template.remove(account);  
  27.     }  
  28.     public List<Account> getAllAccounts(){  
  29.         List<Account> accounts =template.find("select acc from Account acc");  
  30.         return accounts;  
  31.     }  
  32. }  

4) persistence.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <persistence xmlns="http://java.sun.com/xml/ns/persistence"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  
  5.     http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">  
  6.       
  7.     <persistence-unit name="ForAccountsDB">  
  8.         <mapping-file>com/javatpoint/Account.xml</mapping-file>  
  9.         <class>com.javatpoint.Account</class>  
  10.     </persistence-unit>  
  11. </persistence>  

5) applicationContext.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"   
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:tx="http://www.springframework.org/schema/tx"   
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  7.     http://www.springframework.org/schema/tx  
  8.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
  9.       
  10.      <tx:annotation-driven transaction-manager="jpaTxnManagerBean" proxy-target-class="true"/>  
  11.       
  12.      <bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  13.         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>  
  14.         <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>  
  15.         <property name="username" value="system"></property>  
  16.         <property name="password" value="oracle"></property>  
  17.     </bean>  
  18.            
  19.       <bean id="hbAdapterBean" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">  
  20.         <property name="showSql" value="true"></property>  
  21.         <property name="generateDdl" value="true"></property>  
  22.         <property name="databasePlatform" value="org.hibernate.dialect.OracleDialect"></property>  
  23.      </bean>  
  24.       
  25.     <bean id="emfBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  
  26.         <property name="dataSource" ref="dataSourceBean"></property>  
  27.         <property name="jpaVendorAdapter" ref="hbAdapterBean"></property>  
  28.      </bean>  
  29.        
  30.      <bean id="jpaTemplateBean" class="org.springframework.orm.jpa.JpaTemplate">  
  31.         <property name="entityManagerFactory" ref="emfBean"></property>  
  32.      </bean>  
  33.        
  34.      <bean id="accountsDaoBean" class="com.javatpoint.AccountsDao">  
  35.         <property name="template" ref="jpaTemplateBean"></property>  
  36.      </bean>  
  37.       <bean id="jpaTxnManagerBean" class="org.springframework.orm.jpa.JpaTransactionManager">  
  38.         <property name="entityManagerFactory" ref="emfBean"></property>  
  39.     </bean>  
  40.           
  41. </beans>  
The generateDdl property will create the table automatically.
The showSql property will show the sql query on console.

6) Accountsclient.java
  1. package com.javatpoint;  
  2.   
  3. import java.util.List;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  6. import org.springframework.context.support.FileSystemXmlApplicationContext;  
  7.   
  8. public class AccountsClient{  
  9. public static void main(String[] args){  
  10.  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  11.  AccountsDao accountsDao = context.getBean("accountsDaoBean",AccountsDao.class);  
  12.           
  13.  accountsDao.createAccount(15"Jai Kumar"41000);  
  14.  accountsDao.createAccount(20"Rishi "35000);  
  15.  System.out.println("Accounts created");  
  16.           
  17.  //accountsDao.updateBalance(20, 50000);  
  18.  //System.out.println("Account balance updated");  
  19.           
  20.           
  21.  /*List<Account> accounts = accountsDao.getAllAccounts(); 
  22.  for (int i = 0; i < accounts.size(); i++) { 
  23.    Account acc = accounts.get(i); 
  24.    System.out.println(acc.getAccountNumber() + " : " + acc.getOwner() + " (" + acc.getBalance() + ")"); 
  25.  }*/  
  26.           
  27.   //accountsDao.deleteAccount(111);  
  28.   //System.out.println("Account deleted");  
  29.           
  30.  }  
  31. }  

Output

Hibernate: insert into account100 (balance, owner, accountnumber) values (?, ?, ?)
Hibernate: insert into account100 (balance, owner, accountnumber) values (?, ?, ?)
Accounts created

No comments:

Post a Comment

Note: only a member of this blog may post a comment.