English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring Data JPA 튜토리얼

Spring Data JPA API는 JpaTemplate 클래스를 제공하여 Spring 애플리케이션과 JPA를 통합합니다.

JPA(Java Persistence API)는 Sun이企業 애플리케이션에서 객체를 영구화하는 데 사용하는 스펙입니다. 현재는 복잡한 엔티티 벤의 대체자로 사용되고 있습니다.

JPA 스펙의 구현을 제공하는 많은 공급자가 있습니다. 예를 들어:

Hibernate Toplink iBatis OpenJPA와 같은

Spring JpaTemplate의 장점

Object를 Persistence 인스턴스, EntityManagerFactory 인스턴스, EntityTransaction 인스턴스, EntityManager 인스턴스를 생성하고, EntityTransaction 인스턴스를 커밋하고 EntityManager를 닫는 등, 페어사이드 코드를 작성하지 않고도 영구화, 업데이트, 제거 또는 검색할 수 있습니다.

따라서 그것 많은 코드를 절약했습니다

이 예제에서는 Hibernate 모드를 사용하여 JPA를 구현할 것입니다.

Spring과 JPA 통합 예제

Spring应用程序과 JPA를 통합하는 간단한 단계를 확인해 보겠습니다:

Account.java 파일을 생성하십시오 Account.xml 파일을 생성하십시오 AccountDao.java 파일을 생성하십시오 persistence.xml 파일을 생성하십시오 applicationContext.xml 파일을 생성하십시오 AccountsClient.java 파일을 생성하십시오

이 예제에서는休眠 애플리케이션을 spring과 통합하겠습니다. spring와 함께 jpa 예제를 확인해 보겠습니다。 디렉토리 구조

1、Account.java

이는 간단한 POJO 클래스입니다。

package com.w3codebox;
public class Account {
	private int accountNumber;
	private String owner;
	private double balance;
        //no-arg와 파라미터화된 생성자
        //getter 및 setter
}
2、Account.xml

이 맵핑 파일은 모든 상속 클래스의 정보를 포함하고 있습니다。

<entity-mappings version="1.0" 
		xmlns="http://java.sun.com/xml/ns/persistence/orm" 
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance 
		xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm 
		http://java.sun.com/xml/ns/persistence/orm_1_0.xsd ">
	<entity class="com.w3codebox.Account">
		<table name="account100"></table>
		<attributes>
			<id name="accountNumber">
				<column name="accountnumber"/>
			</id>
			<basic name="owner">
				<column name="owner"/>
			</basic>
			<basic name="balance">
				<column name="balance"/>
			</basic>
		</attributes>
	</entity>
</entity-mappings>

3、AccountDao.java

package com.w3codebox;
import java.util.List;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class AccountsDao{
	JpaTemplate template;
	public void setTemplate(JpaTemplate template) {
		this.template = template;
	}
	public void createAccount(int accountNumber, String owner, double balance) {
		Account account = new Account(accountNumber,owner,balance);
		template.persist(account);
	}
	public void updateBalance(int accountNumber,double newBalance){
		Account account = template.find(Account.class, accountNumber);
		if(account != null){
			account.setBalance(newBalance);
		}
		template.merge(account);
	}
	public void deleteAccount(int accountNumber){
		Account account = template.find(Account.class, accountNumber);
		if(account != null)
			template.remove(account);
	}
	public List<Account> getAllAccounts(){
		List<Account> accounts =template.find("select acc from Account acc");
		return accounts;
	}
}

4、persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
    
	<persistence-unit name="ForAccountsDB">
		<mapping-file>com/w3codebox/Account.xml</mapping-file>
		<class>com.w3codebox.Account</class>
	</persistence-unit>
</persistence>

5、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:tx="http://www.springframework.org/schema/tx" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 	 <tx:annotation-driven transaction-manager="jpaTxnManagerBean" proxy-target-class="true"/>
	 <bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="jdbc:oracle:thin:@localhost:<1521:xe"></property>
		<property name="username" value="system"></property>
		<property name="password" value="oracle"></property>
	</bean>
	 	 
 	  <bean id="hbAdapterBean" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
	 	<property name="showSql" value="true"></property>
	 	<property name="generateDdl" value="true"></property>
	 	<property name="databasePlatform" value="org.hibernate.dialect.OracleDialect"></property>
	 </bean>
	<bean id="emfBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
	 	<property name="dataSource" ref="dataSourceBean"></property>
	 	<property name="jpaVendorAdapter" ref="hbAdapterBean"></property>
	 </bean>
	 
	 <bean id="jpaTemplateBean" class="org.springframework.orm.jpa.JpaTemplate">
 	 	<property name="entityManagerFactory" ref="emfBean"></property>
 	 </bean>
 	 
 	 <bean id="accountsDaoBean" class="com.w3codebox.AccountsDao">
 	 	<property name="template" ref="jpaTemplateBean"></property>
 	 </bean>
 	  <bean id="jpaTxnManagerBean" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="emfBean"></property>
	</bean>
 	 	
</beans>

generateDdl 속성이 테이블을 자동으로 생성합니다.

showSql 속성이 제어台中 sql 쿼리를 표시합니다.

6、Accountsclient.java

package com.w3codebox;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AccountsClient{
public static void main(String[] args){
 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 AccountsDao accountsDao = context.getBean("accountsDaoBean",AccountsDao.class);
 accountsDao.createAccount(15, "Jai Kumar", 41000);
 accountsDao.createAccount(20, "Rishi ", 35000);
 System.out.println("Accounts created");
 //accountsDao.updateBalance(20, 50000);
 //System.out.println("Account balance updated");
 /*List<Account> accounts = accountsDao.getAllAccounts();
 for (int i = 0; i < accounts.size(); i++) {
   Account acc = accounts.get(i);
   System.out.println(acc.getAccountNumber() + " : " + acc.getOwner() + " (" + acc.getBalance() + )
 }*/
  //accountsDao.deleteAccount(111);
  //System.out.println("Account deleted");
 }
}

출력

Hibernate: account에 insert into100 (잔액, 소유자, 계정 번호) 값 (?, ?, ?)
Hibernate: account에 insert into100 (잔액, 소유자, 계정 번호) 값 (?, ?, ?)
계정 생성