Spring Data 学习

Spring Data支持类似Hibernate的查询语句,也可以写原生SQL语句,下面记录典型的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
 * 1. Repository 是一个空接口. 即是一个标记接口
 * 2. 若我们定义的接口继承了 Repository, 则该接口会被 IOC 容器识别为一个 Repository Bean.
 * 纳入到 IOC 容器中. 进而可以在该接口中定义满足一定规范的方法. 
 
 * 3. 实际上, 也可以通过 @RepositoryDefinition 注解来替代继承 Repository 接口
 */
/**
 * 在 Repository 子接口中声明方法
 * 1. 不是随便声明的. 而需要符合一定的规范
 * 2. 查询方法以 find | read | get 开头
 * 3. 涉及条件查询时,条件的属性用条件关键字连接
 * 4. 要注意的是:条件属性以首字母大写。
 * 5. 支持属性的级联查询. 若当前类有符合条件的属性, 则优先使用, 而不使用级联属性. 
 * 若需要使用级联属性, 则属性之间使用 _ 进行连接. 
 */
//@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)
public interface PersonRepsotory extends 
    JpaRepository<Person, Integer>,
    JpaSpecificationExecutor<Person>, PersonDao{
//已定义private PersonRepsotory personRepsotory = ctx.getBean(PersonRepsotory.class);;
    //根据 lastName 来获取对应的 Person
    Person getByLastName(String lastName);
    //Person person = personRepsotory.getByLastName("AA");
     
    //WHERE lastName LIKE ?% AND id < ?
    List<Person> getByLastNameStartingWithAndIdLessThan(String lastName, Integer id);
    //List<Person> persons = personRepsotory.getByLastNameStartingWithAndIdLessThan("X", 10);
     
    //WHERE lastName LIKE %? AND id < ?
    List<Person> getByLastNameEndingWithAndIdLessThan(String lastName, Integer id);
    //List<Person> persons = personRepsotory.getByLastNameEndingWithAndIdLessThan("X", 10);
     
    //WHERE email IN (?, ?, ?) OR birth < ?
    List<Person> getByEmailInAndBirthLessThan(List<String> emails, Date birth);
    //persons = personRepsotory.getByEmailInAndBirthLessThan(Arrays.asList("[email protected]", "[email protected]", "[email protected]"), new Date());
     
    //WHERE a.id > ?
    List<Person> getByAddress_IdGreaterThan(Integer id);
    //List<Person> persons = personRepsotory.getByAddress_IdGreaterThan(1);
     
    //查询 id 值最大的那个 Person
    //使用 @Query 注解可以自定义 JPQL 语句以实现更灵活的查询
    @Query("SELECT p FROM Person p WHERE p.id = (SELECT max(p2.id) FROM Person p2)")
    Person getMaxIdPerson();
    //Person person = personRepsotory.getMaxIdPerson();
     
    //为 @Query 注解传递参数的方式1: 使用占位符. 
    @Query("SELECT p FROM Person p WHERE p.lastName = ?1 AND p.email = ?2")
    List<Person> testQueryAnnotationParams1(String lastName, String email);
    //List<Person> persons = personRepsotory.testQueryAnnotationParams1("AA", "[email protected]");
     
    //为 @Query 注解传递参数的方式1: 命名参数的方式. 
    @Query("SELECT p FROM Person p WHERE p.lastName = :lastName AND p.email = :email")
    List<Person> testQueryAnnotationParams2(@Param("email") String email, @Param("lastName") String lastName);
    //List<Person> persons = personRepsotory.testQueryAnnotationParams2("[email protected]", "AA");
     
    //SpringData 允许在占位符上添加 %%. 
    @Query("SELECT p FROM Person p WHERE p.lastName LIKE %?1% OR p.email LIKE %?2%")
    List<Person> testQueryAnnotationLikeParam(String lastName, String email);
    //List<Person> persons = personRepsotory.testQueryAnnotationLikeParam("A", "bb");
     
    //SpringData 允许在占位符上添加 %%. 
    @Query("SELECT p FROM Person p WHERE p.lastName LIKE %:lastName% OR p.email LIKE %:email%")
    List<Person> testQueryAnnotationLikeParam2(@Param("email") String email, @Param("lastName") String lastName);
    //List<Person> persons = personRepsotory.testQueryAnnotationLikeParam2("bb", "A");
     
    //设置 nativeQuery=true 即可以使用原生的 SQL 查询
    @Query(value="SELECT count(id) FROM jpa_persons", nativeQuery=true)
    long getTotalCount();
    //long count = personRepsotory.getTotalCount();
     
    //可以通过自定义的 JPQL 完成 UPDATE 和 DELETE 操作. 注意: JPQL 不支持使用 INSERT
    //在 @Query 注解中编写 JPQL 语句, 但必须使用 @Modifying 进行修饰. 以通知 SpringData, 这是一个 UPDATE 或 DELETE 操作
    //UPDATE 或 DELETE 操作需要使用事务, 此时需要定义 Service 层. 在 Service 层的方法上添加事务操作. 
    //默认情况下, SpringData 的每个方法上有事务, 但都是一个只读事务. 他们不能完成修改操作!
    @Modifying
    @Query("UPDATE Person p SET p.email = :email WHERE id = :id")
    void updatePersonEmail(@Param("id") Integer id, @Param("email") String email);
    //personRepsotory.updatePersonEmail("[email protected]", 1);//会抛异常,删除和修改时要加事务
}

删除和修改操作要加事务,写在Service中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//先配置自动扫描
@Service
public class PersonService {
 
    @Autowired
    private PersonRepsotory personRepsotory;
     
    @Transactional
    public void savePersons(List<Person> persons){
        personRepsotory.save(persons);
    }
     
    @Transactional
    public void updatePersonEmail(String email, Integer id){
        personRepsotory.updatePersonEmail(id, email);
    }
}


分页和排序,PersonRepository实现PagingAndSortingRespository接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
    public void testPagingAndSortingRespository(){
        //pageNo 从 0 开始. 
        int pageNo = 6 1;
        int pageSize = 5;
        //Pageable 接口通常使用的其 PageRequest 实现类. 其中封装了需要分页的信息
        //排序相关的. Sort 封装了排序的信息
        //Order 是具体针对于某一个属性进行升序还是降序. 
        Order order1 = new Order(Direction.DESC, "id");
        Order order2 = new Order(Direction.ASC, "email");
        Sort sort = new Sort(order1, order2);
         
        PageRequest pageable = new PageRequest(pageNo, pageSize, sort);
        Page<Person> page = personRepsotory.findAll(pageable);
         
        System.out.println("总记录数: " + page.getTotalElements());
        System.out.println("当前第几页: " + (page.getNumber() + 1));
        System.out.println("总页数: " + page.getTotalPages());
        System.out.println("当前页面的 List: " + page.getContent());
        System.out.println("当前页面的记录数: " + page.getNumberOfElements());
    }


JpaRepository接口

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
public void testJpaRepository(){
    Person person = new Person();
    person.setBirth(new Date());
    person.setEmail("[email protected]");
    person.setLastName("xyz");
    person.setId(28);
    //数据库中已经存在id为28的记录,执行update
    Person person2 = personRepsotory.saveAndFlush(person);
     
    System.out.println(person == person2);
    //false
}


JpaSpecificationExecutor接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * 目标: 实现带查询条件的分页. id > 5 的条件
 
 * 调用 JpaSpecificationExecutor 的 Page<T> findAll(Specification<T> spec, Pageable pageable);
 * Specification: 封装了 JPA Criteria 查询的查询条件
 * Pageable: 封装了请求分页的信息: 例如 pageNo, pageSize, Sort
 */
@Test
public void testJpaSpecificationExecutor(){
    int pageNo = 3 1;
    int pageSize = 5;
    PageRequest pageable = new PageRequest(pageNo, pageSize);
     
    //通常使用 Specification 的匿名内部类
    Specification<Person> specification = new Specification<Person>() {
        /**
         * @param *root: 代表查询的实体类. 
         * @param query: 可以从中可到 Root 对象, 即告知 JPA Criteria 查询要查询哪一个实体类. 还可以
         * 来添加查询条件, 还可以结合 EntityManager 对象得到最终查询的 TypedQuery 对象. 
         * @param *cb: CriteriaBuilder 对象. 用于创建 Criteria 相关对象的工厂. 当然可以从中获取到 Predicate 对象
         * @return: *Predicate 类型, 代表一个查询条件. 
         */
        @Override
        public Predicate toPredicate(Root<Person> root,
                CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path path = root.get("id");
            Predicate predicate = cb.gt(path, 5);
            return predicate;
        }
    };
     
    Page<Person> page = personRepsotory.findAll(specification, pageable);
     
    System.out.println("总记录数: " + page.getTotalElements());
    System.out.println("当前第几页: " + (page.getNumber() + 1));
    System.out.println("总页数: " + page.getTotalPages());
    System.out.println("当前页面的 List: " + page.getContent());
    System.out.println("当前页面的记录数: " + page.getNumberOfElements());
}


为某一个 Repository上添加自定义方法

步骤:

-定义一个接口: 声明要添加的, 并自实现的方法

-提供该接口的实现类: 类名需在要声明的 Repository 后添加 Impl, 并实现方法

-声明 Repository 接口, 并继承 1) 声明的接口

-使用. 

-注意: 默认情况下, Spring Data 会在 base-package 中查找 "接口名Impl" 作为实现类. 也可以通过 repository-impl-postfix 声明后缀. 

Spring Data 学习

PersonDao接口

1
2
3
4
5
public interface PersonDao {
     
    void test();
     
}

PersonRepsotoryImpl类实现PersonDao接口

1
2
3
4
5
6
7
8
9
10
11
12
public class PersonRepsotoryImpl implements PersonDao {
     
    @PersistenceContext
    private EntityManager entityManager;
     
    @Override
    public void test() {
        Person person = entityManager.find(Person.class11);
        System.out.println("-->" + person);
    }
 
}

PersonRepsotory接口继承PersonDao接口就可以使用自定义的方法

测试

1
2
3
4
@Test
public void testCustomRepositoryMethod(){
    personRepsotory.test();
}


为所有的 Repository 都添加自实现的方法

步骤:

-声明一个接口, 在该接口中声明需要自定义的方法, 且该接口需要继承 Spring Data 的 Repository.

-提供 1) 所声明的接口的实现类. 且继承 SimpleJpaRepository, 并提供方法的实现

-定义 JpaRepositoryFactoryBean 的实现类, 使其生成 1) 定义的接口实现类的对象

-修改 <jpa:repositories /> 节点的 factory-class 属性指向 3) 的全类名

-注意: 全局的扩展实现类不要用 Imp 作为后缀名, 或为全局扩展接口添加 @NoRepositoryBean 注解告知  Spring Data: Spring Data 不把其作为 Repository