3. JPA 와 SpringData 통합 빠 른 입문

14583 단어 jpaspringdata
지난 절 에 JPA 와 Spring 의 통합 으로 DAO 층 에 사용 되 었 다 는 개념 을 말 했 습 니 다. 여기 서 reposcory 로 대체 할 것 입 니 다. 성명 인터페이스 로 CRUD 를 진행 하 는 것 이 얼마나 간편 한 지 알 게 될 것 입 니 다. 쓸데없는 소리 하지 말고 코드 실전 을 시작 하 세 요. \ (^ o ^) / ~
만리장성 웹 프로젝트 SpringData 01 을 새로 만 들 고 해당 jar 패 키 지 를 / WebContent / WEB - INF / lib 디 렉 터 리 에 넣 습 니 다.
antlr-2.7.7.jar c3p0-0.9.2.1.jar com.springsource.net.sf.cglib-2.2.0.jar com.springsource.org.aopalliance-1.0.0.jar com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar commons-logging-1.1.3.jar dom4j-1.6.1.jar hibernate-c3p0-4.2.4.Final.jar hibernate-commons-annotations-4.0.2.Final.jar hibernate-core-4.2.4.Final.jar hibernate-entitymanager-4.2.4.Final.jar hibernate-jpa-2.0-api-1.0.1.Final.jar javassist-3.15.0-GA.jar jboss-logging-3.1.0.GA.jar jboss-transaction-api_1.1_spec-1.0.1.Final.jar mchange-commons-java-0.2.3.4.jar mysql-connector-java-5.1.7-bin.jar slf4j-api-1.6.1.jar spring-aop-4.0.0.RELEASE.jar spring-aspects-4.0.0.RELEASE.jar spring-beans-4.0.0.RELEASE.jar spring-context-4.0.0.RELEASE.jar spring-core-4.0.0.RELEASE.jar spring-data-commons-1.6.2.RELEASE.jar spring-data-jpa-1.4.2.RELEASE.jar spring-expression-4.0.0.RELEASE.jar spring-jdbc-4.0.0.RELEASE.jar spring-orm-4.0.0.RELEASE.jar spring-tx-4.0.0.RELEASE.jar spring-web-4.0.0.RELEASE.jar spring-webmvc-4.0.0.RELEASE.jar
2. 웹. xml 설정 을 잊 으 면 안 됩 니 다.
        
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpirngData01</display-name>
  
  <!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:application.xml</param-value>
	</context-param>

	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

3. application. 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:context="http://www.springframework.org/schema/context"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:repository="http://www.springframework.org/schema/data/repository"
	xsi:schemaLocation="http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.6.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
   <!--       -->
   <context:component-scan base-package="com.tan.springdata"/>
   <!--    properties   -->
   <context:property-placeholder location="classpath:db.properties"/>
  <!--       -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  	<property name="user" value="${jdbc.user}"></property>
  	<property name="password" value="${jdbc.password}"></property>
  	<property name="driverClass" value="${jdbc.driverClass}"></property>
  	<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>	
  	<property name="minPoolSize" value="${jdbc.minPoolSize}"></property>	
	<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
  </bean>
  
  <!--         (     )  -->
  <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  	<!--            -->
    <property name="dataSource" ref="dataSource"></property>
    <!--       -->
   <property name="packagesToScan" value="com.tan.springdata.entities"></property>
   <!--JPA    -->
  	<property name="jpaVendorAdapter">
  		<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
  	</property>
   <!--  JPA   Hibernate        -->
   <property name="jpaProperties">
  	<props>
  		<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
		<prop key="hibernate.hbm2ddl.auto">update</prop>
		<prop key="hibernate.show_sql">true</prop>
		<prop key="hibernate.format_sql">true</prop>
		<!-- *              .   : lastName - last_name -->
		<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
  	</props>
  
   </property>
  </bean>
  <!--    Spring JPA        -->
  <bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  	<property name="entityManagerFactory" ref="entityManagerFactory"/>
  </bean>
  
  <!--        repository      -->
  <jpa:repositories base-package="com.tan.springdata.repositories"
	  	entity-manager-factory-ref="entityManagerFactory"
	  	transaction-manager-ref="jpaTransactionManager"/>
	  	
  <!--        -->
  <tx:annotation-driven transaction-manager="jpaTransactionManager"/>

 
</beans>

4. 위 에 db. properties 를 사 용 했 습 니 다.
jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///jpa2

jdbc.minPoolSize=5
jdbc.maxPoolSize=10

5. Entity 를 완성 해 야 합 니 다. 그렇지 않 으 면 계속 할 수 없습니다. 저 는 보류 하지 않 고 모두 hh 를 붙 일 것 입 니 다 ~
  Person.java
package com.tan.springdata.entities;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Table(name="JPA_PERSONS")
@Entity
public class Person {

	private Integer id;
	private String lastName;

	private String email;
	private Date birth;

	private Address address;

	@GeneratedValue(strategy=GenerationType.AUTO)
	@Id
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Temporal(TemporalType.DATE)
	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", lastName=" + lastName+"]";
	}

	
	@JoinColumn(name="ADDRESS_ID")
	@ManyToOne
	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}
	
	private String addressCity;

	public String getAddressCity() {
		return addressCity;
	}

	public void setAddressCity(String addressCity) {
		this.addressCity = addressCity;
	}
	
}

Address.java
package com.tan.springdata.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name="JPA_ADDRESS")
@Entity
public class Address {

	private Integer id;
	private String city;
	private String province;

	@GeneratedValue(strategy=GenerationType.AUTO)
	@Id
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

}

6. 이제 자신의 Repository 를 만 들 때 가 되 었 습 니 다.
package com.tan.springdata.repositories;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.tan.springdata.entities.Person;
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer>{
	 //      Person  
	Person getByLastName(String lastName);
	
	//          
	List<Person>getByLastNameStartingWith(String ln); 
	
	//           
	List<Person>getByLastNameLike(String ln);
	
	//addressCity
	//address -> city
	List<Person> getByAddress_City(String city);
	
	//--------------------JPQL--------------------
	@Query("SELECT p FROM Person p WHERE p.birth = (SELECT min(p2.birth) FROM Person p2)")
	List<Person> getMaxAgePersons();
	
	//      Service     ,     
	//        
	@Modifying
	@Query("UPDATE Person p SET p.lastName = ?1 WHERE p.id = ?2")
	void updatePersonLastName(String ln, int id);
	
	//        
	@Modifying
	@Query("UPDATE Person p SET p.email = :e WHERE p.id = :id")
	void updatePersonEmail(@Param("id") Integer id, @Param("e") String email);

	
    //    SQL      
	@Modifying
	@Query(value="DELETE FROM jpa_persons WHERE last_name = ?1", nativeQuery=true)
	void deleteByLastNameWithNativeSQL(String lastName);
		
}

7. 관련 업 무 를 처리 하려 면 서 비 스 를 추가 해 야 합 니 다. 누가 우리 에 게 업무 가 없다 고 했 지만 추가 해 야 합 니 다. 왜냐하면 대사 가 이것 이 '사상' 이 라 고 말 했 기 때 문 입 니 다.
package com.tan.springdata.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tan.springdata.entities.Person;
import com.tan.springdata.repositories.PersonRepository;

@Service
@Transactional
public class PersonService {
	
	@Autowired
	private PersonRepository personRepository;
	
	public void saveOrUpdate(Person person){
		personRepository.save(person);
	}
	
	public Person getByLastName(String lastName){
		return personRepository.getByLastName(lastName);
	}
	
	 public List<Person>getByLastNameStartingWith(String ln){
		 return personRepository.getByLastNameStartingWith(ln);
		
	 }
	 
	 public List<Person>getByLastNameLike(String ln){
		return personRepository.getByLastNameLike(ln);
	 }
	
	 
	 public List<Person>getAddressCity(String city){
		 return personRepository.getByAddress_City(city);
	 }
	//--------------------JPQL--------------------
	 //           
	 public List<Person>getMaxAgePersons(){
		 return personRepository.getMaxAgePersons();
	 }
	 
	 //  id  lastName
	 public void updateLastName(String lastName, Integer id){
		personRepository.updatePersonLastName(lastName, id);
	}
	//  id  Email
	 public void updateEmail(String email, Integer id){
			personRepository.updatePersonEmail(id, email);
	}
	//          
	 public void delete(String lastName){
			personRepository.deleteByLastNameWithNativeSQL(lastName);
	}
}

8. 자, Testing 시작...
package com.tan.springdata.test;
import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.tan.springdata.entities.Address;
import com.tan.springdata.entities.Person;
import com.tan.springdata.repositories.PersonRepository;
import com.tan.springdata.services.PersonService;

public class SpringDataTesting {
	
	private ApplicationContext ctx=null;
	private PersonService personService;
	private PersonRepository personRepository=null;
	
	{
		ctx=new ClassPathXmlApplicationContext("application.xml");
		personService=ctx.getBean(PersonService.class);
		personRepository=ctx.getBean(PersonRepository.class);
	}
	
	
	@Test
	public void testQueryBylastName() {
		Person person = personService.getByLastName("tan");
		System.out.println(person);
		
		String addressCity = person.getAddressCity();
		System.out.println(addressCity);

	}
	@Test
	public void getByLastNameStartingWith() {
		List<Person> person = personService.getByLastNameStartingWith("t");
		for(Person p:person){
			System.out.println(p);
		}	
	}
	
	@Test
	public void getByLastNameLike() {
		List<Person> person = personService.getByLastNameLike("%a%");
		for(Person p:person){
			System.out.println(p);
		}
	}	
	@Test
	public void getAddressCity() {
		List<Person> person = personService.getAddressCity("  ");
		for(Person p:person){
			System.out.println(p);
		}
	}	
   //------------------JPQL  --------------------------------------
	@Test
	public void getMaxAgePersons() {
		List<Person> maxAgePersons = personService.getMaxAgePersons();
		for(Person p:maxAgePersons){
			System.out.println(p);
		}
	}
	@Test
	public void updateLastName() {
		personService.updateLastName("tanzhengqaing", 1);
	}	
	@Test
	public void updateLastNddame() {
		personService.updateEmail("[email protected]", 1);
	}	
	
    //                  
	@Test
	public void delete() {
		personService.delete("tan");
	}	
		
}

    본인 테스트, 전부 통과, 부족 한 점 이 있 으 면 큰 소 에 게 지적 해 주세요!마지막 으로, 공 부 는 공유 하 는 것 이 중요 합 니 다. 여러분, 소중 한 의견 을 많이 제시 하 세 요 O (∩ ∩) O ~

좋은 웹페이지 즐겨찾기