您的位置:首页 > 编程语言 > ASP

spring data 接口之 JpaRepository,JpaSpecificationExecutor

2018-04-04 00:00 736 查看
package org.zgf.spring.data.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.zgf.spring.data.entity.StudentPO;

/**
* JpaRepository 继承于 PagingAndSortingRepository 接口,
* 由于JpaSpecificationExecutor 并不继承repository 接口,所以它不能单独使用,只能和jpa Repository 一起用
*/
public interface IStudentJpaRepository extends JpaRepository<StudentPO, Integer>, JpaSpecificationExecutor<StudentPO> {
/** JpaRepository 主要特点,将返回类型 Iterable 转换成了List, 并新增了写方法
* List<T> findAll();
* List<T> findAll(Sort sort);
* List<T> findAll(Iterable<ID> ids);
* <S extends T> List<S> save(Iterable<S> entities);
* void flush();
* <S extends T> S saveAndFlush(S entity);
* void deleteInBatch(Iterable<T> entities);
* void deleteAllInBatch();
* T getOne(ID id);
*/
/** JpaSpecificationExecutor 实现了带条件的查询
*  T findOne(Specification<T>);
*  List<T> findAll(Specification<T>);
*  List<T> findAll(Specification<T>, Sort);
*  List<T> findAll(Specification<T>, Pageable);
*  long count(Specification<T>);
*/
}

测试类

package org.zgf.spring.data.dao;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.zgf.spring.data.base.BaseTest;
import org.zgf.spring.data.dao.IStudentJpaRepository;
import org.zgf.spring.data.entity.StudentPO;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

public class Test_IStudentJpaRepository extends BaseTest {

@Autowired
private IStudentJpaRepository studentJpaSpecification;

@Test
public void test_findAll() {
Specification<StudentPO> specification = new Specification<StudentPO>() {
@Override
public Predicate toPredicate(Root<StudentPO> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path path = root.get("id");
Predicate predicate = cb.lt(path, 5);
return predicate;
}
};
List<StudentPO> studentList = this.studentJpaSpecification.findAll(specification);
for (StudentPO studentPO : studentList) {
System.out.println(studentPO);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring data