springboot jpa 多条件查询(多表)
前几天写的,贴上来。
实体类。
package com.syl.demo.daomain; import lombok.Data; import javax.persistence.*; /**
* Created by 孙义朗 on 2017/10/31.
*/
@Entity
@Data
public class User {
@Id
private String userId;
private String userName;
private String password;
private String gender;//性别
private String age;
@ManyToOne
private School school;
@ManyToOne
private Grade grade;
}
User
package com.syl.demo.daomain; import lombok.Data; import javax.jws.soap.SOAPBinding;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany; /**
* Created by 孙义朗 on 2017/10/31.
*/
@Data
@Entity
public class School {
@Id
private String schoolId;
private String schoolName; }
School
package com.syl.demo.daomain; import lombok.Data; import javax.persistence.*; /**
* Created by 孙义朗 on 2017/11/16.
*/
@Entity
@Data
public class Grade {
@Id
private String gradeId;
private String gradeName;
@ManyToOne
private School school; }
Grade
还有一个封装查询条件的类
package com.syl.demo.daomain; import lombok.Data; import javax.persistence.Id; /**
* Created by 孙义朗 on 2017/11/16 0016.
*/
@Data
public class Params {
private String userId;
private String userName;
private String gender;
private String age; private String gradeName; private String schoolName; }
Params
Dao层
package com.syl.demo.dao; import com.syl.demo.daomain.Grade;
import com.syl.demo.daomain.School;
import com.syl.demo.daomain.User;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /**
* Created by 孙义朗 on 2017/11/16 0016.
*/
public interface UserRepository extends JpaRepository<User,String> {
List<User> findAll(); List<User> findAll(Specification<User> spc, Pageable pageable); }
UserRepository
Service及实现
package com.syl.demo.service; import com.syl.demo.daomain.Grade;
import com.syl.demo.daomain.Params;
import com.syl.demo.daomain.School;
import com.syl.demo.daomain.User;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification; import java.util.List; /**
* Created by 孙义朗 on 2017/11/16 0016.
*/
public interface UserService {
List<User> findAll(); List<User> findAll(int pageNum, int pageSize,User user); List<User> findAll(int pageNum, int pageSize, Params params); }
UserService
package com.syl.demo.service.impl; import com.syl.demo.dao.UserRepository;
import com.syl.demo.daomain.Grade;
import com.syl.demo.daomain.Params;
import com.syl.demo.daomain.School;
import com.syl.demo.daomain.User;
import com.syl.demo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service; import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List; /**
* Created by 孙义朗 on 2017/11/16 0016.
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository; @Override
public List<User> findAll() {
return userRepository.findAll();
} //查询User,单表,多条件
@Override
public List<User> findAll(int pageNum, int pageSize, User user) {
Pageable pageable = new PageRequest(pageNum, pageSize);
List<User> uList = userRepository.findAll(new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<>();
if (user.getUserId() != null && !user.getUserId().equals("")) {
predicates.add(cb.like(root.get("userId").as(String.class), "%" + user.getUserId() + "%"));
}
if (user.getUserName() != null && !user.getUserName().equals("")) {
predicates.add(cb.like(root.get("userName").as(String.class), "%" + user.getUserName() + "%"));
}
if (user.getGender() != null && !user.getGender().equals("")) {
predicates.add(cb.like(root.get("gender").as(String.class), "%" + user.getGender() + "%"));
}
if (user.getAge() != null && !user.getAge().equals("")) {
predicates.add(cb.like(root.get("age").as(String.class), "%" + user.getAge() + "%"));
}
Predicate[] pre = new Predicate[predicates.size()];
criteriaQuery.where(predicates.toArray(pre));
return cb.and(predicates.toArray(pre));
}
}, pageable); return uList;
} //查询User,多表,多条件
@Override
public List<User> findAll(int pageNum, int pageSize, Params params) {
Pageable pageable = new PageRequest(pageNum, pageSize);
List<User> uList = userRepository.findAll(new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<>();
//根据userId 查询user
if (StringUtils.isNotBlank(params.getUserId())) {
list.add(cb.equal(root.get("userId").as(String.class), params.getUserId()));
}
//根据userName 模糊查询user
if (StringUtils.isNotBlank(params.getUserName())) {
list.add(cb.like(root.get("userName").as(String.class), "%" + params.getUserName() + "%"));
}
//根据gender 查询user
if (StringUtils.isNotBlank(params.getGender())) {
list.add(cb.equal(root.get("gender").as(String.class), params.getGender()));
}
//根据age>? 查询user
if (StringUtils.isNotBlank(params.getAge())) {
list.add(cb.gt(root.get("age").as(Integer.class), Integer.valueOf(params.getAge())));
}
//根据gradeName 查询user
if (StringUtils.isNotBlank(params.getGradeName())) {
Join<Grade, User> join = root.join("grade", JoinType.LEFT);
list.add(cb.equal(join.get("gradeName"), params.getGradeName()));
}
//根据schoolName 查询user
if (StringUtils.isNotBlank(params.getSchoolName())) {
Join<School, User> join = root.join("grade", JoinType.LEFT);
list.add(cb.equal(join.get("school").get("schoolName"), params.getSchoolName()));
}
Predicate[] pre = new Predicate[list.size()];
criteriaQuery.where(list.toArray(pre));
return cb.and(list.toArray(pre));
}
}, pageable); return uList;
} }
UserServiceImpl
控制层
package com.syl.demo.controller; import com.syl.demo.daomain.Grade;
import com.syl.demo.daomain.Params;
import com.syl.demo.daomain.School;
import com.syl.demo.daomain.User;
import com.syl.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import java.util.List; /**
* Created by 孙义朗 on 2017/11/16 0016.
*/
@RestController
public class UserController {
@Autowired
UserService userService; @GetMapping(value = "/getUser")
public List<User> getUser() {
List<User> uList = userService.findAll();
return uList;
} //查询User,单表,多条件
@PostMapping(value = "/getUser/{pageNum}/{pageSize}")
public List<User> getUser(@PathVariable("pageNum") Integer pageNum,
@PathVariable("pageSize") Integer pageSize,
@RequestBody User user) {
List<User> uList = userService.findAll(pageNum, pageSize, user);
return uList;
} //查询User,多表,多条件
@PostMapping(value = "/getUser2/{pageNum}/{pageSize}")
public List<User> getUser2(@PathVariable("pageNum") Integer pageNum,
@PathVariable("pageSize") Integer pageSize,
@RequestBody Params params) {
List<User> uList = userService.findAll(pageNum, pageSize, params);
return uList;
} }
UserController
完成。
postman测试效果如下
(单表查询http://www.cnblogs.com/arrrrrya/p/7831248.html)
springboot jpa 多条件查询(多表)的更多相关文章
- springboot jpa 多条件查询(单表)
需要实现的功能: 多个搜索输入框:全部不填,则查出所有列表:填了条件,就按条件查找:填的条件个数不定. 方法实现的核心:jpa自带的Specification<T> (目前只需要单表,多表 ...
- jpa多条件查询重写Specification的toPredicate方法(转)
Spring Data JPA支持JPA2.0的Criteria查询,相应的接口是JpaSpecificationExecutor.Criteria 查询:是一种类型安全和更面向对象的查询 . 这个接 ...
- jpa多条件查询
首先继承JpaSpecificationExecutor<T>接口 需要用到JpaSpecificationExecutor<T>中的Page<T> findAll ...
- Spring Boot Jpa 多条件查询+排序+分页
事情有点多,于是快一个月没写东西了,今天补上上次说的. JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将 ...
- spring data jpa 组合条件查询封装
/** * 定义一个查询条件容器 * @author lee * * @param <T> */ public class Criteria<T> implements Spe ...
- spring jpa : 多条件查询
https://www.cnblogs.com/Donnnnnn/p/6277872.html 方式一: 第一步:EmpAccNumService package com.payease.scford ...
- springboot后端实现条件查询,要配合使用mybatis
package cn.com.dyg.work.sqlgen; import cn.com.dyg.work.common.exception.DefException; import cn.com. ...
- springBoot JPA PageAble分页查询出错,PropertyReferenceException: No property creation found for type
PropertyReferenceException: No property creation found for type @RequestParam(required = false, defa ...
- SpringBoot JPA + 分页 + 单元测试SpringBoot JPA条件查询
application.properties 新增数据库链接必须的参数 spring.jpa.properties.hibernate.hbm2ddl.auto=update 表示会自动更新表结构,所 ...
随机推荐
- AndroidPn推送测试
服务器搭建好了之后,往客户端推送.按照里面自带的一个client,可以分别在模拟器和真机上分别测试,不过由于这个框架真的不是很完善,会遇到各种问题. (1) 其中还遇到了一个安卓模拟器的问题,启动模拟 ...
- artdialog(4.1.7)弹出框
artDialog弹出框 <link href="/js/artDialog/skins/default.css" rel="stylesheet" /& ...
- 解决EF没有生成字段和表说明
找了很多资料,终于找到一篇真正能解决ef生成字段说明,注释的文章,收藏不了,于是转载 本文章为转载,原文地址 项目中使用了EF框架,使用的是Database-First方式,因为数据库已经存在,所以采 ...
- .net图表之ECharts随笔09-pie环形图表
这是最后的效果图 1. 这里title属性用到了富文本标签 官方文档是用的label属性,看得我一开始格外的懵逼.后面我尝试着在text中写入格式,没想到竟然成功了. rich中定义样式,在text中 ...
- 使用客户端软件向服务端php程序发送post数据,php接受三种方法
方法一:$_POST; 方法二:$GLOBALS['HTTP_RAW_POST_DATA'],需要在php.ini开启 always_populate_raw_post_data = On: 方法三: ...
- 使用chosen插件实现多级联动和置位
使用chosen插件实现多级联动和置位 首先写好第一个select,加上onchage属性之后,写onchange方法. <select data-placeholder="选择省份. ...
- UWP开发入门(九)——简单界面的布局技巧及屏幕适应
嘿嘿嘿,题目比较绕哈.本篇主要讨论一般情况下,页面的布局技巧,怎么将元素的展现尽量做到分辨率无关.基本的思路仍然是尽量少的标定具体的数字,而是用比列来标注各元素占据的空间. 这里我打算用易信的名片页来 ...
- item style edit in sharepoint 2013
标题头添加属性:(如果需要使用ddwrt)xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime&quo ...
- ovs 源mac, 目的src 互换
push:NXM_OF_ETH_SRC[],push:NXM_OF_ETH_DST[],pop:NXM_OF_ETH_SRC[],pop:NXM_OF_ETH_DST[] 1:把src mac推到栈顶 ...
- APP间传递消息
https://www.jianshu.com/p/d640ccfcea5f 1: URL Scheme 常用的App间传值方式.常见于分享等. 2: Keychain 借助系统类 Keychain ...