spring data 接口之 JpaRepository,JpaSpecificationExecutor

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>);
     */
}

測試類java

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);
}
    }
}
相關文章
相關標籤/搜索