三、JPA和SpringData集成快速入门

   上节说到用JPA和Spring的集成使用到了DAO层的概念,在这里将会用repository来代替,你会发现以声明接口的方式去进行CRUD是多么的简便,废话少说开始代码实战吧,\(^o^)/~


一、万里长征始于 新建一个Web项目SpringData01,把相应的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

二、配置web.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>

三、配置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>

四、上面用到了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

五、还是得整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;
	}

}

六、是时候该建立自己的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);
		
}

七、处理相关业务还是得加Service,谁说我们这里没有什么业务,但是也要加,因为大师说这是“思想”.

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);
	}
}

八、好了,开始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~


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。