• Spring Data


    目录

    一、Spring Data 介绍

    二、搭建 Spring Data JPA 环境

    三、Repository 接口

    四、Query 注解

    五、CrudRepository接口

    六、PagingAndSortingRepository 接口

    七、JpaSpecificationExecutor 接口


    一、Spring Data 介绍

    Spring Data : Spring 的一个子项目。用于简化数据库访问,支持NoSQL 和 关系数据存储。其主要目标是使数据库的访问变得方便快捷。开发者唯一要做的,就是声明持久层的接口,其他都交给 Spring Data JPA 来帮你完成!

    SpringData 项目所支持 NoSQL 存储:

    • MongoDB (文档数据库)

    • Neo4j(图形数据库)

    • Redis(键/值存储)

    • Hbase(列族数据库)

    SpringData 项目所支持的关系数据存储技术:

    • JDBC

    • JPA

    二、搭建 Spring Data JPA 环境

    1. 使用Maven构建项目,项目名为:springdatajpa

    2. 配置 pom.xml

      
          5.2.6.RELEASE
          5.4.10.Final
          8.0.21
          3.8.1
          1.0.1.Final
          1.7.25
          1.9.5
          UTF-8
          UTF-8
          1.8
          1.8
      
          
          
              org.springframework
              spring-context
              ${spring.version}
          
          
              org.springframework
              spring-beans
              ${spring.version}
          
          
              org.springframework
              spring-core
              ${spring.version}
          
          
              org.springframework
              spring-jdbc
              ${spring.version}
          
          
              org.springframework
              spring-aop
              ${spring.version}
          
          
              org.springframework
              spring-tx
              ${spring.version}
          
          
              org.springframework
              spring-orm
              ${spring.version}
          
          
              org.springframework
              spring-test
              ${spring.version}
          
          
              org.springframework.data
              spring-data-jpa
              2.2.5.RELEASE
          
          
          
              org.hibernate
              hibernate-core
              ${hibernate.version}
          
          
              org.hibernate
              hibernate-entitymanager
              ${hibernate.version}
          
          
              org.hibernate
              hibernate-hikaricp
              ${hibernate.version}
          
          
              org.hibernate
              hibernate-ehcache
              ${hibernate.version}
          
          
              org.hibernate.javax.persistence
              hibernate-jpa-2.0-api
              ${jpa.version}
          
          
              mysql
              mysql-connector-java
              ${mysql.version}
          
          
              org.ehcache
              ehcache
              ${ehcache.version}
          
          
              org.slf4j
              slf4j-api
              ${slf4j.version}
          
          
              org.aspectj
              aspectjweaver
              ${aspectj.version}
          
          
              org.projectlombok
              lombok
              1.18.12
          
          
              junit
              junit
              4.12
              test
          
      
    3. 创建 com.javakc.springdatajpa 包

    4. 创建 entity 包并在其目录下创建实体类

    5. 创建 dao 包并在其目录下创建接口继承 JpaRepository 接口

    6. 在 resources 目录下创建 jdbc.properties 配置文件

      jdbc.driverClass=com.mysql.cj.jdbc.Driver
      jdbc.jdbcUrl=jdbc:mysql:///jpa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
      jdbc.username=root
      jdbc.password=123456
    7. 在 resources 目录下创建 spring-jpa.xml 配置文件

      
      
      ​
          
          
      ​
          
          
      ​
          
          
              
              
              
              
          
      ​
          
          
              
              
                  
              
              
              
                  
                      true
                      true
                      update
                  
              
          
      ​
          
          
              
          
      ​
          
          
      ​
          
          
    8. 创建测试类

      import com.javakc.springdatajpa.repository.JpaRepository;
      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;
      ​
      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(locations = {"classpath:spring-jpa.xml"})
      public class JpaTest {
      ​
          @Autowired
          private StudentDao studentDao;
      ​
          @Test
          public void test() {
          }
      ​
      }

    三、Repository 接口

    Repository 接口是 Spring Data 的一个核心接口,它不提供任何方法,开发者在自己定义的接口中声明需要的方法,只要遵循 Spring Data的规范,就无需写实现类。

    基础的 Repository 提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下:

    • Repository: 仅仅是一个标识,表明任何继承它的均为仓库接口类

    • CrudRepository: 继承 Repository,实现了 CRUD 相关的方法

    • PagingAndSortingRepository: 继承 CrudRepository,实现了分页排序相关的方法

    • JpaRepository: 继承 PagingAndSortingRepository,实现 JPA 规范相关的方法

    • JpaSpecificationExecutor: 不属于Repository体系,实现 JPA Criteria 查询条件相关的方法

    四、Query 注解

    1. 使用 @Query 注解可以自定义 JPQL 语句来实现更灵活的查询,结构更为清晰,这是 Spring data 的特有实现

      @Query("select count(s) from Student s")
      public int getCountStudent();
    2. 索引参数

      @Query("select s from Student s where s.id = ?1 and s.studentName = ?2")
      public Student getStudentParam1(int id, String studentName);
    3. 命名参数

      @Query("select s from Student s where s.id = :id and s.studentName = :studentName")
      public Student getStudentParam2(@Param("id") int id,@Param("studentName") String studentName);
    4. 模糊查询

      @Query("select s from Student s where s.studentName like %?1%")
      public List findStudentParam3(String studentName);
      @Query("select s from Student s where s.studentName like %:studentName%")
      public List findStudentParam4(@Param("studentName") String studentName);
    5. 原生SQL

      @Query(value="select count(id) from jpa_student", nativeQuery=true)
      public int getCountStudent2();

    五、CrudRepository接口

    1. 保存

      @Test
      public void save() {
          Student student = new Student();
          student.setStudentName("小明");
          jpaDao.save(student);
      }
    2. 删除

      @Test
      public void delete() {
          jpaDao.deleteById(1);
      }
    3. 获取单条数据

      @Test
      public void get() {
          Optional o = studentDao.findById(1);
          Student student = o.get();
          System.out.println(student);
      }
    4. 修改

      @Test
      public void update() {
          Student student = new Student();
          student.setId(1);
          student.setStudentName("小红");
          jpaDao.save(student);
      }

    六、PagingAndSortingRepository 接口

    分页与排序

    @Test
    public void testPageAndSort() {
        int pageNo = 1 -1;
        int pageSize = 3;
    
        Sort.Order order1 = new Sort.Order(Sort.Direction.ASC, "id");
        Sort.Order order2 = new Sort.Order(Sort.Direction.ASC, "studentName");
        Sort sort = Sort.by(order1, order2);
    
        Pageable pageable = PageRequest.of(pageNo,pageSize,sort);
        Page page = jpaDao.findAll(pageable);
        System.out.println("总记录数: " + page.getTotalElements());
        System.out.println("总页数: " + page.getTotalPages());
        System.out.println("当前页数据: " + page.getContent());
        System.out.println("当前页记录数: " + page.getNumberOfElements());
    }

    七、JpaSpecificationExecutor 接口

    继承 JpaSpecificationExecutor 接口

    带条件的分页查询

    @Test
    public void testPageAndCriteria() {
        Specification specification = new Specification() {
            /**
             * @param root 要查询的实体类
             * @param criteriaQuery 得到 Root 对象, 告知 JPA Criteria 要查询哪个实体类
             * @param criteriaBuilder 创建 Criteria 对象的工厂, 得到 Predicate 对象
             * @return 表示一个查询条件
             */
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path path = root.get("studentName");
                Predicate predicate = criteriaBuilder.like(path, "%D%");
                return predicate;
            }
        };
    
        int pageNo = 1 -1;
        int pageSize = 3;
        Pageable pageable = PageRequest.of(pageNo, pageSize);
    
        Page page = jpaDao.findAll(specification, pageable);
        System.out.println("总记录数: " + page.getTotalElements());
        System.out.println("总页数: " + page.getTotalPages());
        System.out.println("当前页数据: " + page.getContent());
        System.out.println("当前页记录数: " + page.getNumberOfElements());
    }

    带条件的分页查询 - 多表关联

    @Test
    public void testPageAndCriteria2() {
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                // ## 动态 SQL 表达式
                Predicate predicate = criteriaBuilder.conjunction();
                // ## 动态 SQL 表达式集合
                List> expressionList = predicate.getExpressions();
                
                Join join = root.join("classRoom", JoinType.LEFT);
                expressionList.add(criteriaBuilder.equal(join.get("classRoomName"), "javakc"));
                return predicate;
            }
        };
        int pageNo = 1 -1;
        int pageSize = 3;
        Pageable pageable = PageRequest.of(pageNo, pageSize);
    
        Page page = jpaDao.findAll(specification, pageable);
        System.out.println("总记录数: " + page.getTotalElements());
        System.out.println("总页数: " + page.getTotalPages());
        System.out.println("当前页数据: " + page.getContent());
        System.out.println("当前页记录数: " + page.getNumberOfElements());
    }

  • 相关阅读:
    CDC实战:MySQL实时同步数据到Elasticsearch之数组集合(array)如何处理【CDC实战系列十二】
    webpack实战:最新QQ音乐sign参数加密分析
    RHCE之路从服务器,selinux
    Yolov5如何训练自定义的数据集,以及使用GPU训练,涵盖报错解决
    Linux 中的 chown 命令及示例
    Day39——Dp专题
    uniapp使用nfc功能及详解
    Qt专栏3—Qt项目创建Hello World
    【开源日记】宿舍断电自动关灯设备(二)
    从小白到程序员的攻略(适合自学编程的网站)
  • 原文地址:https://blog.csdn.net/CZW2181119177/article/details/126172336