SpingDataJpa

蔚落 2022-05-24 23:05 9阅读 0赞

SpringDataJpa


  • SpringDataJpa
  • 简介

    • 传统数据库访问数据库
    • 使用Spring JDBC Template对数据库进行操作
    • SpringData
    • Repository接口
    • CrudRepository接口
    • PagingAndSortingRepository接口
    • JpaRepository接口
    • JpaSpecificationExecutor接口

简介

Spring Data 是为数据访问提供一种熟悉且一致的基于Spring的编程模型,同时仍然保留底层数据存储的特​​殊特性。它可以轻松使用数据访问技术,可以访问关系和非关系数据库。

Spring Data 又包含多个子项目:

  • Spring Data JPA
  • Spirng Data Mongo DB
  • Spring Data Redis
  • Spring Data Solr

传统数据库访问数据库

使用原始JDBC方式进行数据库操作
创建数据表
这里写图片描述
jdbc工具类

  1. package com.JDBC.util;
  2. import java.io.InputStream;
  3. import java.sql.*;
  4. import java.util.Properties;
  5. public class JDBCUtil {
  6. public static Connection getConnection() throws Exception {
  7. InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
  8. Properties properties = new Properties();
  9. properties.load(inputStream);
  10. String url = properties.getProperty("jdbc.url");
  11. String user = properties.getProperty("jdbc.user");
  12. String password = properties.getProperty("jdbc.password");
  13. String driverClass = properties.getProperty("jdbc.driverClass");
  14. Class.forName(driverClass);
  15. Connection connection = DriverManager.getConnection(url, user, password);
  16. return connection;
  17. }
  18. public static void release(ResultSet resultSet, Statement statement,Connection connection) {
  19. if (resultSet != null) {
  20. try {
  21. resultSet.close();
  22. } catch (SQLException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. if (statement != null) {
  27. try {
  28. statement.close();
  29. } catch (SQLException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. if (connection != null) {
  34. try {
  35. connection.close();
  36. } catch (SQLException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }
  41. }

建立POJO

  1. package com.xx;
  2. public class Student {
  3. private int id;
  4. private String name;
  5. private int age;
  6. public int getId() {
  7. return id;
  8. }
  9. public void setId(int id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public int getAge() {
  19. return age;
  20. }
  21. public void setAge(int age) {
  22. this.age = age;
  23. }
  24. }
  25. package com.xx.dao;
  26. import com.xx.domain.Student;
  27. import com.xx.util.JDBCUtil;
  28. import java.sql.Connection;
  29. import java.sql.PreparedStatement;
  30. import java.sql.ResultSet;
  31. import java.util.ArrayList;
  32. import java.util.List;
  33. public class StudentDAOImpl implements StudentDAO{
  34. /** * 查询学生 */
  35. @Override
  36. public List<Student> query() {
  37. List<Student> students = new ArrayList<>();
  38. Connection connection = null;
  39. PreparedStatement preparedStatement = null;
  40. ResultSet resultSet = null;
  41. String sql = "select * from student";
  42. try {
  43. connection = JDBCUtil.getConnection();
  44. preparedStatement = connection.prepareStatement(sql);
  45. resultSet = preparedStatement.executeQuery();
  46. Student student = null;
  47. while (resultSet.next()) {
  48. int id = resultSet.getInt("id");
  49. String name = resultSet.getString("name");
  50. int age = resultSet.getInt("age");
  51. student = new Student();
  52. student.setId(id);
  53. student.setAge(age);
  54. student.setName(name);
  55. students.add(student);
  56. }
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. }finally {
  60. JDBCUtil.release(resultSet,preparedStatement,connection);
  61. }
  62. return students;
  63. }
  64. /** * 添加学生 */
  65. @Override
  66. public void save(Student student) {
  67. Connection connection = null;
  68. PreparedStatement preparedStatement = null;
  69. ResultSet resultSet = null;
  70. String sql = "insert into student(name,age) values (?,?)";
  71. try {
  72. connection = JDBCUtil.getConnection();
  73. preparedStatement = connection.prepareStatement(sql);
  74. preparedStatement.setString(1, student.getName());
  75. preparedStatement.setInt(2,student.getAge());
  76. preparedStatement.executeUpdate();
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. }finally {
  80. JDBCUtil.release(resultSet,preparedStatement,connection);
  81. }
  82. }
  83. }

使用Spring JDBC Template对数据库进行操作

  • 创建spring配置文件:

    <?xml version=”1.0” encoding=”UTF-8”?>


















  • 编写查询学生和保存学生的方法

    package com.xx.dao;

    import com.xx.domain.Student;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowCallbackHandler;

    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;

  1. public class StudentDAOSpringJdbcImpl implements StudentDAO{
  2. private JdbcTemplate jdbcTemplate;
  3. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  4. this.jdbcTemplate = jdbcTemplate;
  5. }
  6. @Override
  7. public List<Student> query() {
  8. final List<Student> students = new ArrayList<>();
  9. String sql = "select * from student";
  10. jdbcTemplate.query(sql, new RowCallbackHandler() {
  11. @Override
  12. public void processRow(ResultSet resultSet) throws SQLException {
  13. int id = resultSet.getInt("id");
  14. String name = resultSet.getString("name");
  15. int age = resultSet.getInt("age");
  16. Student student = new Student();
  17. student.setId(id);
  18. student.setAge(age);
  19. student.setName(name);
  20. students.add(student);
  21. }
  22. });
  23. return students;
  24. }
  25. @Override
  26. public void save(Student student) {
  27. String sql = "insert into student(name,age) values (?,?)";
  28. jdbcTemplate.update(sql, new Object[]{student.getName(), student.getAge()});
  29. }
  30. }

弊端分析

  • DAO中有太多的代码
  • DAOImpl有大量重复代码
  • 开发分页或者其他功能还要重新封装

SpringData

例:

  • 添加pom依赖


    org.springframework.data
    spring-data-jpa
    1.8.0.RELEASE


    org.hibernate
    hibernate-entitymanager
    4.3.6.Final
  • 创建一个新的spring配置文件

    <?xml version=”1.0” encoding=”UTF-8”?>























    org.hibernate.cfg.ImprovedNamingStrategy
    org.hibernate.dialect.MySQL5InnoDBDialect
    true
    true
    update
















LocalContainerEntityMangaerFactoryBean:

适用于所有环境的FactoryBean,能全面控制EntityMangaerFactory配置,非常适合那种需要细粒度定制的环境。

jpaVendorAdapter:

用于设置JPA实现厂商的特定属性,如设置hibernate的是否自动生成DDL的属性generateDdl,这些属性是厂商特定的。目前spring提供HibernateJpaVendorAdapter,OpenJpaVendorAdapter,EclipseJpaVendorAdapter,TopLinkJpaVenderAdapter四个实现。

jpaProperties:

指定JPA属性;如Hibernate中指定是否显示SQL的“hibernate.show_sql”属性。

  • 建立实体类Employee:

    package com.xx;

  1. public class Employee {
  2. private Integer id;
  3. private String name;
  4. private Integer age;
  5. public Integer getId() {
  6. return id;
  7. }
  8. public void setId(Integer id) {
  9. this.id = id;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public Integer getAge() {
  18. return age;
  19. }
  20. public void setAge(Integer age) {
  21. this.age = age;
  22. }
  23. }
  • 自定义接口并继承Repository 接口
    继承的Repository接口泛型里的第一个参数是要操作的对象,即Employee;第二个参数是主键id的类型,即Integer。
    方法即为根据名字找员工,这个接口是不用写实现类的。为什么可以只继承接口定义了方法就行了呢,因为spring data底层会根据一些规则来进行相应的操作。
    所以方法的名字是不能随便写的,不然就无法执行想要的操作。

    package com.xx.repository;

    import com.zzh.domain.Employee;
    import org.springframework.data.repository.Repository;

    public interface EmployeeRepository extends Repository{

    1. Employee findByName(String name);

    }

  • 创建测试类
    findByName方法体中先不用写,直接执行空的测试方法,我们的Employee表就自动被创建了,此时表中没有数据,向里面添加一条数据用于测试:这里写图片描述

    package com.xx.repository;

  1. import com.xx.domain.Employee;
  2. import org.junit.After;
  3. import org.junit.Before;
  4. import org.junit.Test;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;
  7. public class EmployeeRepositoryTest {
  8. private ApplicationContext ctx = null;
  9. private EmployeeRepository employeeRepository = null;
  10. @Before
  11. public void setUp() throws Exception {
  12. ctx = new ClassPathXmlApplicationContext("beans-new.xml");
  13. employeeRepository = ctx.getBean(EmployeeRepository.class);
  14. }
  15. @After
  16. public void tearDown() throws Exception {
  17. ctx = null;
  18. }
  19. @Test
  20. public void findByName() throws Exception {
  21. Employee employee = employeeRepository.findByName("zhangsan");
  22. System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());
  23. }
  24. }

再执行测试方法中的内容:
这里写图片描述

Repository接口

  • Repository接口是Spring Data的核心接口,不提供任何方法
  • 使用 @ RepositoryDefinition注解跟继承Repository是同样的效果,例如 @ RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
  • Repository接口定义为:public interface Repository

Repository的子接口
这里写图片描述

  • CrudRepository :继承 Repository,实现了CRUD相关的方法。
  • PagingAndSortingRepository : 继承 CrudRepository,实现了分页排序相关的方法。
  • JpaRepository :继承 PagingAndSortingRepository ,实现了JPA规范相关的方法。

这里写图片描述

Repository中查询方法定义规则
上面一个例子中使用了findByName作为方法名进行指定查询,但是如果把名字改为其他没有规则的比如test就无法获得正确的查询结果。

有如下规则:

这里写图片描述

最右边是sql语法,中间的就是spring data操作规范,现在写一些小例子来示范一下:

先在employee表中初始化了一些数据:
这里写图片描述

在继承了Repository接口的EmployeeRepository接口中新增一个方法:
这里写图片描述
条件是名字以test开头,并且年龄小于22岁,在测试类中进行测试:
这里写图片描述
得到结果:
这里写图片描述
在换一个名字要在某个范围以内并且年龄要小于某个值:这里写图片描述
测试类:
这里写图片描述
得到结果,只有test1和test2,因为在test1,test2和test3里面,年龄还要小于22,所以test3被排除了:
这里写图片描述
弊端分析
对于按照方法名命名规则来使用的弊端在于:

  1. 方法名会比较长
  2. 对于一些复杂的查询很难实现

Query注解

  • 只需要将 @ Query标记在继承了Repository的自定义接口的方法上,就不再需要遵循查询方法命名规则。
  • 支持命名参数及索引参数的使用
  • 本地查询

案例

  • 查询Id最大的员工信息

    @Query(“select o from Employee o where id=(select max(id) from Employee t1)”) Employee getEmployeeById();

注意: Query语句中第一个Employee是类名

测试类:

  1. @Test
  2. public void getEmployeeByMaxId() throws Exception {
  3. Employee employee = employeeRepository.getEmployeeByMaxId();
  4. System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());
  5. }
  • 根据占位符进行查询

注意: 占位符从1开始

  1. @Query("select o from Employee o where o.name=?1 and o.age=?2")
  2. List<Employee> queryParams1(String name, Integer age);

测试方法:

  1. @Test
  2. public void queryParams1() throws Exception {
  3. List<Employee> employees = employeeRepository.queryParams1("zhangsan", 20);
  4. for (Employee employee : employees) {
  5. System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());
  6. }
  7. }
  • 根据命名参数的方式

    @Query(“select o from Employee o where o.name=:name and o.age=:age”) List queryParams2(@Param(“name”) String name, @Param(“age”) Integer age);

  • like查询语句

    @Query(“select o from Employee o where o.name like %?1%”)

    1. List<Employee> queryLike1(String name);

    @Test

    1. public void queryLike1() throws Exception {
    2. List<Employee> employees = employeeRepository.queryLike1("test");
    3. for (Employee employee : employees) {
    4. System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());
    5. }
    6. }
  • like语句使用命名参数

    @Query(“select o from Employee o where o.name like %:name%”) List queryLike2(@Param(“name”) String name);

本地查询

所谓本地查询,就是使用原生的sql语句进行查询数据库的操作。但是在Query中原生态查询默认是关闭的,需要手动设置为true:

  1. @Query(nativeQuery = true, value = "select count(1) from employee")
  2. long getCount();

更新操作整合事物使用

  • 在DAO中定义方法根据Id来更新年龄(Modifying注解代表允许修改)

    @Modifying @Query(“update Employee o set o.age = :age where o.id = :id”) void update(@Param(“id”) Integer id, @Param(“age”) Integer age);

要注意,执行更新或者删除操作是需要事物支持,所以通过service层来增加事物功能,在update方法上添加Transactional注解。

  1. package com.xx.service;
  2. import com.xx.repository.EmployeeRepository;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. @Service
  6. public class EmployeeService {
  7. @Autowired
  8. private EmployeeRepository employeeRepository;
  9. @Transactional
  10. public void update(Integer id, Integer age) {
  11. employeeRepository.update(id,age);
  12. }
  13. }
  • 删除操作

    删除操作同样需要Query注解,Modifying注解和Transactional注解

    @Modifying

    1. @Query("delete from Employee o where o.id = :id")
    2. void delete(@Param("id") Integer id);
  1. @Transactional
  2. public void delete(Integer id) {
  3. employeeRepository.delete(id);
  4. }

CrudRepository接口

这里写图片描述

  • 创建接口继承CrudRepository

    package com.xx.repository;

  1. import com.xx.domain.Employee;
  2. import org.springframework.data.repository.CrudRepository;
  3. public interface EmployeeCrudRepository extends CrudRepository<Employee,Integer>{
  4. }
  • 在service层中调用

    @Autowired

    1. private EmployeeCrudRepository employeeCrudRepository;
  • 存入多个对象

    @Transactional

    1. public void save(List<Employee> employees) {
    2. employeeCrudRepository.save(employees);
    3. }
  • 创建测试类,将要插入的100条记录放在List中:

    package com.xx.repository;

    import com.xx.domain.Employee;
    import com.xx.service.EmployeeService;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    import java.util.ArrayList;
    import java.util.List;

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration({
  3. "classpath:beans-new.xml"})
  4. public class EmployeeCrudRepositoryTest {
  5. @Autowired
  6. private EmployeeService employeeService;
  7. @Test
  8. public void testSave() {
  9. List<Employee> employees = new ArrayList<>();
  10. Employee employee = null;
  11. for (int i = 0; i < 100; i++) {
  12. employee = new Employee();
  13. employee.setName("test" + i);
  14. employee.setAge(100 - i);
  15. employees.add(employee);
  16. }
  17. employeeService.save(employees);
  18. }
  19. }

执行后:
这里写图片描述
CrudRepository总结

可以发现在自定义的EmployeeCrudRepository中,只需要声明接口并继承CrudRepository就可以直接使用了。

PagingAndSortingRepository接口

  • 该接口包含分页和排序的功能
  • 带排序的查询:findAll(Sort sort)
  • 带排序的分页查询:findAll(Pageable pageable)

    自定义接口

    package com.xx.repository;

  1. import com.xx.domain.Employee;
  2. import org.springframework.data.repository.PagingAndSortingRepository;
  3. public interface EmployeePagingAndSortingRepository extends PagingAndSortingRepository<Employee, Integer> {
  4. }

测试类:

分页

  1. package com.xx.repository;
  2. import com.xx.domain.Employee;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.domain.Page;
  7. import org.springframework.data.domain.PageRequest;
  8. import org.springframework.data.domain.Pageable;
  9. import org.springframework.test.context.ContextConfiguration;
  10. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  11. @RunWith(SpringJUnit4ClassRunner.class)
  12. @ContextConfiguration({
  13. "classpath:beans-new.xml"})
  14. public class EmployeePagingAndSortingRepositoryTest {
  15. @Autowired
  16. private EmployeePagingAndSortingRepository employeePagingAndSortingRepository;
  17. @Test
  18. public void testPage() {
  19. //第0页,每页5条记录
  20. Pageable pageable = new PageRequest(0, 5);
  21. Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
  22. System.out.println("查询的总页数:"+ page.getTotalPages());
  23. System.out.println("总记录数:"+ page.getTotalElements());
  24. System.out.println("当前第几页:"+ page.getNumber()+1);
  25. System.out.println("当前页面对象的集合:"+ page.getContent());
  26. System.out.println("当前页面的记录数:"+ page.getNumberOfElements());
  27. }
  28. }

排序:

在PageRequest的构造函数里还可以传入一个参数Sort,而Sort的构造函数可以传入一个Order,Order可以理解为关系型数据库中的Order;Order的构造函数Direction和property参数代表按照哪个字段进行升序还是降序。

现在按照id进行降序排序:

  1. @Test
  2. public void testPageAndSort() {
  3. Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
  4. Sort sort = new Sort(order);
  5. Pageable pageable = new PageRequest(0, 5, sort);
  6. Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
  7. System.out.println("查询的总页数:"+ page.getTotalPages());
  8. System.out.println("总记录数:"+ page.getTotalElements());
  9. System.out.println("当前第几页:" + page.getNumber() + 1);
  10. System.out.println("当前页面对象的集合:"+ page.getContent());
  11. System.out.println("当前页面的记录数:"+ page.getNumberOfElements());
  12. }

JpaRepository接口

这里写图片描述

  • 创建接口继承JpaRepository

    package com.xx.repository;

  1. import com.xx.domain.Employee;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. public interface EmployeeJpaRepository extends JpaRepository<Employee,Integer>{
  4. }
  • 测试类:

    package com.xx.repository;

    import com.xx.domain.Employee;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration({
  3. "classpath:beans-new.xml"})
  4. public class EmployeeJpaRepositoryTest {
  5. @Autowired
  6. private EmployeeJpaRepository employeeJpaRepository;
  7. @Test
  8. public void testFind() {
  9. Employee employee = employeeJpaRepository.findOne(99);
  10. System.out.println(employee);
  11. }
  12. }

查看员工是否存在

  1. @Test
  2. public void testExists() {
  3. Boolean result1 = employeeJpaRepository.exists(25);
  4. Boolean result2 = employeeJpaRepository.exists(130);
  5. System.out.println("Employee-25: " + result1);
  6. System.out.println("Employee-130: " + result2);
  7. }

JpaSpecificationExecutor接口

  • Specification封装了JPA Criteria查询条件
  • 没有继承其他接口。

    自定义接口

    这里要尤为注意,为什么我除了继承JpaSpecificationExecutor还要继承JpaRepository,就像前面说的,JpaSpecificationExecutor没有继承任何接口,如果我不继承JpaRepository,那也就意味着不能继承Repository接口,spring就不能进行管理,后面的自定义接口注入就无法完成。

    package com.xx.repository;

  1. import com.xx.domain.Employee;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  4. public interface EmployeeJpaSpecificationExecutor extends JpaSpecificationExecutor<Employee>,JpaRepository<Employee,Integer> {
  5. }

测试类

测试结果包含分页,降序排序,查询条件为年龄大于50

  1. package com.xx.repository;
  2. import com.xx.domain.Employee;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.domain.Page;
  7. import org.springframework.data.domain.PageRequest;
  8. import org.springframework.data.domain.Pageable;
  9. import org.springframework.data.domain.Sort;
  10. import org.springframework.data.jpa.domain.Specification;
  11. import org.springframework.test.context.ContextConfiguration;
  12. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  13. import javax.persistence.criteria.*;
  14. @RunWith(SpringJUnit4ClassRunner.class)
  15. @ContextConfiguration({
  16. "classpath:beans-new.xml"})
  17. public class EmployeeJpaSpecificationExecutorTest {
  18. @Autowired
  19. private EmployeeJpaSpecificationExecutor employeeJpaSpecificationExecutor;
  20. /** * 分页 * 排序 * 查询条件: age > 50 */
  21. @Test
  22. public void testQuery() {
  23. Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
  24. Sort sort = new Sort(order);
  25. Pageable pageable = new PageRequest(0, 5, sort);
  26. /** * root:查询的类型(Employee) * query:添加查询条件 * cb:构建Predicate */
  27. Specification<Employee> specification = new Specification<Employee>() {
  28. @Override
  29. public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
  30. Path path = root.get("age");
  31. return cb.gt(path, 50);
  32. }
  33. };
  34. Page<Employee> page = employeeJpaSpecificationExecutor.findAll(specification, pageable);
  35. System.out.println("查询的总页数:"+ page.getTotalPages());
  36. System.out.println("总记录数:"+ page.getTotalElements());
  37. System.out.println("当前第几页:" + page.getNumber() + 1);
  38. System.out.println("当前页面对象的集合:"+ page.getContent());
  39. System.out.println("当前页面的记录数:"+ page.getNumberOfElements());
  40. }
  41. }

发表评论

表情:
评论列表 (有 0 条评论,9人围观)

还没有评论,来说两句吧...

相关阅读