一、SpringData的环境搭建
依赖增加:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
beans.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:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="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">
<!--1.装备数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_data"/>
</bean>
<!--2.装备EntityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.hcx"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<!--方言-->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<!--履行时显现sql-->
<prop key="hibernate.show_sql">true</prop>
<!--格式化sql-->
<prop key="hibernate.format_sql">true</prop>
<!--自动创立表:依据实体创立表-->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!--3.装备业务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--4.支持注解的业务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--5.装备spring data-->
<jpa:repositories base-package="com.hcx" entity-manager-factory-ref="entityManagerFactory"/>
<context:component-scan base-package="com.hcx"/>
</beans>
Employee:
package com.hcx.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* 雇员:开发实体类,经过实体类自动生成数据表
* Created by HCX on 2019/3/11.
*/
@Entity
public class Employee {
private Integer id;
private String name;
private Integer age;
@Id //主键
@GeneratedValue //自增
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length = 20) //设置该字段的长度
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
repository:
package com.hcx.repository;
import com.hcx.domain.Employee;
import org.springframework.data.repository.Repository;
/**
* Created by HCX on 2019/3/11.
*/
public interface EmployeeRepository extends Repository<Employee,Integer> {
//Repository<Employee,Integer> 操作的实体类和主键
/**
* 依据姓名查找职工
* @param name 姓名
* @return
*/
public Employee findByName(String name);
}
EmployeeRepositoryTest:
package com.hcx.repository;
import com.hcx.domain.Employee;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
/**
* Created by HCX on 2019/3/11.
*/
public class EmployeeRepositoryTest {
private ApplicationContext ctx = null;
private EmployeeRepository employeeRepository = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("beans-jpa.xml");
employeeRepository = ctx.getBean(EmployeeRepository.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
@Test
public void testFindByName() throws Exception {
Employee employee = employeeRepository.findByName("zhangsan");
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
二、Spring Data JPA接口
1.Repository接口:
Repository接口是Spring Data的核心接口,不供给任何办法
public interface Repository<T,ID extends Serializable>{}
- T:要处理的实体类
- ID:T中ID的类型
- Repository是一个空接口,标记接口(没有包括办法声明的接口)
@RepositoryDefinition注解的运用
不继承自Repository则可以运用@RepositoryDefinition:
@RepositoryDefinition(domainClass = Employee.class,idClass = Integer.class)
public interface EmployeeRepository {// extends Repository<Employee,Integer>
//Repository<Employee,Integer> 操作的实体类和主键
/**
* 依据姓名查找职工
* @param name 姓名
* @return
*/
public Employee findByName(String name);
}
2.Repository子接口:
①CrudRepository:继承Repository,完成了CRUD相关的办法
②PagingAndSortingRepository:继承CrudRepository,完成了分页排序相关的办法。
③JpaRepository:继承PagingAndSortingRepository,完成JPA标准相关的办法。
3.Repository中查询办法界说规矩和运用
1.SpringData中查询办法名称的界说规矩
EmployeeRepository:
package com.hcx.repository;
import com.hcx.domain.Employee;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;
import java.util.List;
/**
* Created by HCX on 2019/3/11.
*/
@RepositoryDefinition(domainClass = Employee.class,idClass = Integer.class)
public interface EmployeeRepository {// extends Repository<Employee,Integer>
//Repository<Employee,Integer> 操作的实体类和主键
/**
* 依据姓名查找职工
* @param name 姓名
* @return
*/
public Employee findByName(String name);
/**
* 依据姓名和年纪来查询
* @param name 姓名以某个字符最初
* @param age 年纪小于多少
* @return
*/
public List<Employee> findByNameStartingWithAndAgeLessThan(String name,Integer age);
/**
* 依据姓名和年纪来查询
* @param name 姓名以某个字符完毕
* @param age
* @return 年纪小于多少
*/
public List<Employee> findByNameEndingWithAndAgeLessThan(String name,Integer age);
/**
* 依据姓名和年纪来查询
* @param names 姓名在names调集中
* @param age
* @return
*/
public List<Employee> findByNameInOrAgeLessThan(List<String> names,Integer age);
/**
* 依据姓名和年纪来查询
* @param names
* @param age
* @return
*/
public List<Employee> findByNameInAndAgeLessThan(List<String> names,Integer age);
}
单元测试:
@Test
public void testFindByNameStartingWithAndAgeLessThan() throws Exception {
List<Employee> employees = employeeRepository.findByNameStartingWithAndAgeLessThan("test", 23);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
@Test
public void testFindByNameEndingWithAndAgeLessThan() throws Exception {
List<Employee> employees = employeeRepository.findByNameEndingWithAndAgeLessThan("6", 60);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
@Test
public void testFindByNameInOrAgeLessThan() throws Exception {
List<String> names = new ArrayList<String>();
names.add("test1");
names.add("test2");
names.add("test3");
List<Employee> employees = employeeRepository.findByNameInOrAgeLessThan(names, 22);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
@Test
public void testFindByNameInAndAgeLessThan() throws Exception {
List<String> names = new ArrayList<String>();
names.add("test1");
names.add("test2");
names.add("test3");
List<Employee> employees = employeeRepository.findByNameInAndAgeLessThan(names, 22);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
对于按照办法命名规矩来运用的弊端:
- 办法名较长:约好大于装备
- 对于一些杂乱的查询,很难完成
2.运用SpringData完成杂乱查询办法名称的命名
Query注解的运用:
在repository办法中运用,则不需要遵循查询办法命名规矩:
- 只需要将@Query界说在Repository中的办法之上即可
- 支持命名参数及索引参数的运用
- 支持本地查询
EmployeeRepository:
/**
* 查询职工表中id最大的数据
* @return
*/
@Query("select o from Employee o where id=(select max(id) from Employee t1)") //注意:此处Employee是类名
public Employee getEmployeeByMaxId();
/**
* 依据姓名和年纪查询 运用索引参数
* @param name
* @param age
* @return
*/
@Query("select o from Employee o where o.name=?1 and o.age=?2")
public List<Employee> queryParams1(String name,Integer age);
/**
* 依据姓名和年纪查询 运用命名参数
* @param name
* @param age
* @return
*/
@Query("select o from Employee o where o.name=:name and o.age=:age")
public List<Employee> queryParams2(@Param("name") String name, @Param("age") Integer age);
/**
* 含糊查询 运用索引参数
* @param name
* @return
*/
@Query("select o from Employee o where o.name like %?1%")
public List<Employee> queryLike1(String name);
/**
* 含糊查询 运用命名参数
* @param name
* @return
*/
@Query("select o from Employee o where o.name like %:name%")
public List<Employee> queryLike2(@Param("name")String name);
/**
* 运用原生态的方式查询
* @return
*/
@Query(nativeQuery = true,value="select count(1) from employee") //原生态查询,运用表名
public long getCount();
}
EmployeeRepositoryTest:
@Test
public void testGetEmployeeByMaxId() throws Exception {
Employee employee = employeeRepository.getEmployeeByMaxId();
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
@Test
public void testQueryParams1() throws Exception {
List<Employee> employees = employeeRepository.queryParams1("zhangsan", 20);
for (Employee employee:employees) {
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
@Test
public void testQueryParams2() throws Exception {
List<Employee> employees = employeeRepository.queryParams2("zhangsan", 20);
for (Employee employee:employees) {
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
@Test
public void testQueryLike1() throws Exception {
List<Employee> employees = employeeRepository.queryLike1("test");
for (Employee employee:employees) {
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
@Test
public void testQueryLike2() throws Exception {
List<Employee> employees = employeeRepository.queryLike2("test1");
for (Employee employee:employees) {
System.out.println("id:" + employee.getId() + " " +
",name:" + employee.getName()
+ " age:" + employee.getAge());
}
}
@Test
public void testGetCount() throws Exception {
long count = employeeRepository.getCount();
System.out.println("count:"+count);
}
更新及删去操作:
@Modifying注解运用 @Modifying结合@Query注解履行更新操作 @Transaction在Spring Data中的运用
业务在service层中运用
EmployeeRepository:
/**
* 经过id更新年纪
* @param id
* @param age
*/
@Modifying
@Query("update Employee o set o.age=:age where o.id=:id")
public void update(@Param("id")Integer id,@Param("age")Integer age);
EmployeeService:
package com.hcx.service;
import com.hcx.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by HCX on 2019/3/13.
*/
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Transactional
public void update(Integer id,Integer age){
employeeRepository.update(id,age);
}
}
EmployeeServiceTest:
package com.hcx.service;
import com.hcx.domain.Employee;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
/**
* Created by HCX on 2019/3/13.
*/
public class EmployeeServiceTest {
private ApplicationContext ctx = null;
private EmployeeService employeeService = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("beans-jpa.xml");
employeeService = ctx.getBean(EmployeeService.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
@Test
public void testUpdate() throws Exception {
employeeService.update(1, 55);
}
}
三、JPA中的常用接口
1.CrudRepository接口的运用
- save(entity)
- save(entities)
- findOne(id)
- exists(id)
- findAll()
- delete(id)
- delete(entity)
- delete(entities)
- deleteAll()
EmployeeCrudRepository:
package com.hcx.repository;
import com.hcx.domain.Employee;
import org.springframework.data.repository.CrudRepository;
/**
* Created by HCX on 2019/3/14.
*/
public interface EmployeeCrudRepository extends CrudRepository<Employee,Integer>{
}
EmployeeService:
@Transactional
public void save(List<Employee> employees){
employeeCrudRepository.save(employees);
}
testSave:
@Test
public void testSave() {
List<Employee> employees = new ArrayList<Employee>();
Employee employee = null;
for (int i = 0; i < 100; i++) {
employee = new Employee();
employee.setName("test" + 199);
employee.setAge(100);
// employee.setId(1);
employees.add(employee);
}
employeeService.save(employees);
}
2.PagingAndSortingRespository接口的运用
该接口包括分页和排序的功用 带排序的查询:findAll(Sort sort) 带排序的分页查询:findAll(Pageable pageable)
EmployeePagingAndSortingRepository:
package com.hcx.repository;
import com.hcx.domain.Employee;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* Created by HCX on 2019/3/15.
*/
public interface EmployeePagingAndSortingRepository extends PagingAndSortingRepository<Employee,Integer>{
}
EmployeePagingAndSortingRepositoryTest:
package com.hcx.repository;
import com.hcx.domain.Employee;
import com.hcx.service.EmployeeService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.ArrayList;
import java.util.List;
/**
* Created by HCX on 2019/3/14.
*/
public class EmployeePagingAndSortingRepositoryTest {
private ApplicationContext ctx = null;
private EmployeePagingAndSortingRepository employeePagingAndSortingRepository = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("beans-jpa.xml");
employeePagingAndSortingRepository = ctx.getBean(EmployeePagingAndSortingRepository.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
@Test
public void testPage() {
/**
* PageRequest(int page, int size)
* page:从0开始
*/
Pageable pageable = new PageRequest(0,5);
Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
System.out.println("查询的总页数:"+page.getTotalPages());
System.out.println("查询的总记载数"+page.getTotalElements());
System.out.println("当时第几页"+page.getNumber());
System.out.println("当时页面的调集"+page.getContent());
System.out.println("当时页面的记载数"+page.getNumberOfElements());
}
@Test
public void testPageAndSort(){
Sort.Order order = new Sort.Order(Sort.Direction.DESC,"id");
Sort sort = new Sort(order);
Pageable pageable = new PageRequest(0,5,sort);
Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
System.out.println("查询的总页数:"+page.getTotalPages());
System.out.println("查询的总记载数"+page.getTotalElements());
System.out.println("当时第几页"+page.getNumber());
System.out.println("当时页面的调集"+page.getContent());
System.out.println("当时页面的记载数"+page.getNumberOfElements());
}
}
3.JpaRespository接口的运用
- findAll
- findAll(Sort sort)
- save(entities)
- flush
- deleteInBatch(entities)
EmployeeJpaRepository:
package com.hcx.repository;
import com.hcx.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* Created by HCX on 2019/3/15.
*/
public interface EmployeeJpaRepository extends JpaRepository<Employee,Integer>{
}
EmployeeJpaRepositoryTest:
package com.hcx.repository;
import com.hcx.domain.Employee;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
/**
* Created by HCX on 2019/3/15.
*/
public class EmployeeJpaRepositoryTest {
private ApplicationContext ctx = null;
private EmployeeJpaRepository employeeJpaRepository = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("beans-jpa.xml");
employeeJpaRepository = ctx.getBean(EmployeeJpaRepository.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
@Test
public void testFind(){
Employee employee = employeeJpaRepository.findOne(99);
System.out.println("employee:"+employee);
System.out.println("employee(10):"+employeeJpaRepository.exists(10));
System.out.println("employee(1000):"+employeeJpaRepository.exists(1000));
}
}
4.JpaSpecificationExecutor接口的运用
Specification封装了JPA Criteria查询条件
EmployeeJpaSpecificationExecutorRepository:
package com.hcx.repository;
import com.hcx.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* Created by HCX on 2019/3/15.
*/
public interface EmployeeJpaSpecificationExecutorRepository
extends JpaRepository<Employee,Integer>,JpaSpecificationExecutor<Employee>{
}
EmployeeJpaSpecificationExecutorRepositoryTest:
package com.hcx.repository;
import com.hcx.domain.Employee;
import com.hcx.service.EmployeeService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.*;
import static org.junit.Assert.*;
/**
* Created by HCX on 2019/3/15.
*/
public class EmployeeJpaSpecificationExecutorRepositoryTest {
private ApplicationContext ctx = null;
private EmployeeJpaSpecificationExecutorRepository employeeJpaSpecificationExecutorRepository = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("beans-jpa.xml");
employeeJpaSpecificationExecutorRepository = ctx.getBean(EmployeeJpaSpecificationExecutorRepository.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
@Test
public void testQuery() {
Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
Sort sort = new Sort(order);
Pageable pageable = new PageRequest(0, 5, sort);
Specification<Employee> specification = new Specification<Employee>() {
/**
*
* @param root 要查询的条件(Employee)
* @param criteriaQuery 增加查询条件
* @param criteriaBuilder 构建Predicate
* @return
*/
@Override
public Predicate toPredicate(Root<Employee> root,
CriteriaQuery<?> criteriaQuery,
CriteriaBuilder criteriaBuilder) {
//root(employee(age))
Path path = root.get("age");
Predicate predicate = criteriaBuilder.gt(path, 50);
return predicate;
}
};
Page<Employee> page = employeeJpaSpecificationExecutorRepository.findAll(specification,pageable);
System.out.println("查询的总页数:" + page.getTotalPages());
System.out.println("查询的总记载数" + page.getTotalElements());
System.out.println("当时第几页" + page.getNumber());
System.out.println("当时页面的调集" + page.getContent());
System.out.println("当时页面的记载数" + page.getNumberOfElements());
}
}
补充:
更新操作时,先查询出来,再设置某个特点,此时updateTime不会自动更新,这是需要在实体上加上@DynamicUpdate注解
运用lombok插件简化实体的书写:
xml:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
在IDEA中运用需要安装相应的插件
经过在实体上加上@Data注解,简化get()、set()、toString()等办法的书写
如果只想省略get办法,可以运用@Getter注解
@Entity
@DynamicUpdate
@Data
public class ProductCategory {
/** 类目id. */
@Id //主键
@GeneratedValue //自增
private Integer categoryId;
/** 类目姓名. */
private String categoryName;
/** 类目编号. */
private Integer categoryType;
private Date createTime;
private Date updateTime;
}
Demo链接:github.com/GitHongcx/s…