Spring Data下---Spring Data JPA的使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/CSDN_GIA/article/details/88585752

Spring Data下—Spring Data JPA的使用

一、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中查询方法名称的定义规则

查询规则定义和使用.png

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链接:https://github.com/GitHongcx/springdataDemo

注:本文部分内容来自慕课网

展开阅读全文

没有更多推荐了,返回首页