SpringBoot JPA实现SQL中的NOT IN

Updated on in 杂七杂八 with 1,212 views

最近使用SpringBoot JPA作为开发框架,遇到not in的情况,发现CriteriaBuilder 并没有not in的方法,只有in的方法,然后各种尝试,最终通过阅读源码,根据框架notLike的实现,然后推理出实现not in的方法!!! 其实并不难,主要是看不懂英文文档是硬伤啊!!!

具体实现代码如下:

		List<Long> userIds =new ArrayList();
		userIds.add(1L);
		userIds.add(2L);
		userIds.add(3L);
        Specification<User> specification =(root, query, cb) -> {
        	// 指定in需要的字段
           CriteriaBuilder.In<Long> in = cb.in(root.get("id"));
           // 设置值
           for (Long userId: userIds ) {
               in.value(userId);
           }
           //生成查询
           return query.where(in.not()).getRestriction();
       	};
       	//TODO 然后将这个specification  传给repository 即可实现not in

PS: not exists 也可以如此实现


标题:SpringBoot JPA实现SQL中的NOT IN
作者:hjljy
地址:https://www.aliuying.com/articles/2021/08/12/1628750762376.html

Responses
取消