SpringData-仕様インターフェース動的クエリ入門デモ

前回の記事SpringDataJPAエントリのデモ に基づいて、仕様の動的クエリについて引き続き学習します。

 

次に、前の記事で確立した開発環境に基づいて、新しいテストパッケージを作成し、仕様インターフェイスの動的クエリエントリのデモを学習します。

1.新しいテストクラスを作成します

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpecTest {

    @Autowired
    private CustomerDao customerDao;


}

1.単一条件クエリオブジェクト-equal (String str、String str);

@Test
public void testFindByCondition() {
    Specification<Customer> spec = new Specification<Customer>() {
        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path<Object> custName = root.get("custName");
            Predicate predicate = cb.equal(custName, "张三");
            return predicate;
        }
    };
    Customer customer = customerDao.findOne(spec);
    System.out.println(customer);
}

2.マルチコンディションクエリオブジェクト-and (Predicate p1、Predicate p2); or(Predicate p1、Predicate p2);

@Test
public void testFindBySeveralCondition() {
    Specification<Customer> spec = new Specification<Customer>() {
        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path<Object> custName = root.get("custName");
            Path<Object> custIndustry = root.get("custIndustry");
            Predicate p1 = cb.equal(custName, "张三");
            Predicate p2 = cb.equal(custIndustry, "it行业");
            Predicate and = cb.and(p1, p2);   //以 与 的形式拼接多个查询条件
            //Predicate or =  cb.or(p1, p2);   //以 或 的形式拼接多个查询条件
            return and;
        }
    };
    Customer customer = customerDao.findOne(spec);
    System.out.println(customer);
}

3.ファジークエリ-like ();

     Sort-  Sort sort = new Sort(Sort.Direction.DESC、sorted field name);

@Test
public void testLike() {
    Specification<Customer> spec = new Specification<Customer>() {
        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path<Object> custName = root.get("custName");
            Predicate like = cb.like(custName.as(String.class), "张%");
            return like;
        }
    };
    //添加排序
    //Sort.Direction.DESC: 倒序
    //Sort.Direction.ASC: 升序
    Sort sort = new Sort(Sort.Direction.DESC, "custName");
    List<Customer> list = customerDao.findAll(spec, sort);
    for (Customer customer : list) {
        System.out.println(customer);
    }
}

4.ページングクエリ

@Test
public void testPage() {
    Specification spec = null;
    Pageable pageable = new PageRequest(0, 10);
    Page<Customer> page = customerDao.findAll(null, pageable);
    System.out.println(page.getContent());  //得到数据集合列表
    System.out.println(page.getTotalElements());  //得到总条数
    System.out.println(page.getTotalPages());  //得到总页数
}

 

ソースのダウンロード:https:  //pan.baidu.com/s/1JLc4zABzZBzoy4JhJNNJpg

 

 

 

おすすめ

転載: blog.csdn.net/weixin_42629433/article/details/84775223