使用SpringDATA JPA条件并连表查询

马上要接手DATA JPA 的项目了,因为写得少,就写了给个关联表查询,话不多说,上代码

这是Spring DATA JPA 的官方文档
官方文档

提前说明:@ManyToOne 和 @ManyToMany等一些映射关系去这篇博客去学习一下
Jpa中ManyToMany和OneToMany的双向控制

pom依赖

  <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
  jpa:
    show-sql: true  #显示sql语句
    hibernate:
      ddl-auto: update
      naming:
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    database: mysql #配置现在所使用的数据库
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

实体类(pojo)

这里有三个实体类,外加一个中间实体类
/**
 * 学生类(用户类)
 */
@Data
@Entity
public class User implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    private String userName;
    private String gander;
    private String age;
    @ManyToOne
    private School school;
    @ManyToOne
    private Grade grade;
}
/**
 * 学校类
 */
@Entity
@Data
public class School implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    private String schoolName;
}
/**
 * 班级类
 */
@Data
@Entity
public class Grade implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    private String gradeName;

    @ManyToOne
    private School school;
}

中间表

/**
 * 还有一个封装查询条件的类
 */
@Data
public class Params {
    private String userId;

    private String userName;

    private String gander;

    private String age;

    private String gradeName;

    private String schoolName;
}

DAO层

继承JpaRepository

public interface UserRepository extends JpaRepository<User,Long>{ //Long 代表你实体类中的id 类型
    List<User> findAll();

    List<User> findAll(Specification<User> spc);
}

serivce

写三个方法,即可

public interface UserService {
    List<User> findAll(); //查所有

    List<User> findAll(User user); //条件单表查询

    List<User> findAll(Params params); //条件多表查询
}

在实现userserivce,本来是要分页查询,因为老朽能力不行,目前还没摸透,在做的时候报org.springframework.data.domain.PageImpl 类型转换错误 ,就先看条件查询吧

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public List<User> findAll(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.getId() != null && !user.getId().equals("")) {
                    predicates.add(cb.like(root.get("id").as(String.class), "%" + user.getId() + "%"));
                }
                if (user.getUserName() != null && !user.getUserName().equals("")) {
               
                    predicates.add(cb.like(root.get("userName").as(String.class), "%" + user.getUserName() + "%"));
                }
                if (user.getGrade() != null && !user.getGrade().equals("")) {
                    predicates.add(cb.like(root.get("gender").as(String.class), "%" + user.getGrade() + "%"));
                }
                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));
            }
        });

        return uList;
    }

    @Override
    public List<User> findAll(Params params) {
        //Pageable pageable = new PageRequest(pageNum, pageSize);
        List<User> all = userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                //根据id 查询user
                if (StringUtils.isEmpty(params.getUserId())) {
                    list.add(criteriaBuilder.equal(root.get("id").as(String.class), params.getUserId()));
                }
                //根据userName 模糊查询user
                if (StringUtils.isEmpty(params.getUserName())) {
                    list.add(criteriaBuilder.like(root.get("userName").as(String.class), "%" + params.getUserName() + "%"));
                }
                //根据gander 查询User
                if (StringUtils.isNotBlank(params.getGander())) {
                    list.add(criteriaBuilder.equal(root.get("gander").as(Integer.class), Integer.valueOf(params.getGander())));
                }
                //根据age>? 查询user
                if (StringUtils.isNotBlank(params.getAge())) {
                    list.add(criteriaBuilder.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(criteriaBuilder.equal(join.get("gradeName"), params.getGradeName()));
                }
                //根据SchoolName 查询user
                if (StringUtils.isNotBlank(params.getSchoolName())) {
                    Join<School, User> join = root.join("grade", JoinType.LEFT);
                    list.add(criteriaBuilder.equal(join.get("school").get("schoolName"), params.getSchoolName()));
                }
                Predicate[] predicates = new Predicate[list.size()];
                criteriaQuery.where(list.toArray(predicates));
                return criteriaBuilder.and(list.toArray(predicates));
            }
        });

        return all;
    }

最后,控制层

@RestController
@Log4j2
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    public Result finAll(){
        try {
            return new Result(true, StatusCode.OK,"查询成功", userService.findAll());
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return new Result(false,StatusCode.LOGINERROR,"系统内部出项错误,请稍后再试!",null);
        }
    }

    @RequestMapping(value = "/findByOneAll",method = RequestMethod.GET)
    public Result findByOneAll(@RequestBody User user){
        try {
            return new Result(true,StatusCode.OK,"查询成功",userService.findAll(user));
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return new Result(false,StatusCode.LOGINERROR,"系统内部出项错误,请稍后再试!",null);
        }
    }
    @RequestMapping(value = "/findByTwoAll",method = RequestMethod.GET)
    public Result findByTwoAll(@RequestBody  Params params){
        try {
            return new Result(true,StatusCode.OK,"查询成功",userService.findAll(params));
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return new Result(false,StatusCode.LOGINERROR,"系统内部出项错误,请稍后再试!",null);
        }
    }

Result一个返回结果,我也放在着了

public class Result {
    private boolean flag;
    private Integer code;
    private String message;
    private Object data;
  /*午餐构造*/
    public Result() {
    }
    /*试用于增删改查的代餐构造*/
    public Result(boolean flag, Integer code, String message, Object data) {
        this.flag = flag;
        this.code = code;
        this.message = message;
        this.data = data;
    }
/*试用于增删改的代餐构造*/
    public Result(boolean flag, Integer code, String message) {
        this.flag = flag;
        this.code = code;

        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}
@Data
public class PageResult<T> {
    private long page;//当前页
    private long total;//总页数
    private List<T> rows;//当前页集合

    public PageResult() {
    }

    public PageResult(long page, long total, List<T> rows) {
        this.page = page;
        this.total = total;
        this.rows = rows;
    }
}

public class StatusCode {
    public static final int OK=20000;//成功
    public static final int ERROR =20001;//失败
    public static final int LOGINERROR =20002;//用户名或密码错误
    public static final int ACCESSERROR =20003;//权限不足
    public static final int REMOTEERROR =20004;//远程调用失败
    public static final int REPERROR =20005;//重复操作
}

使用postman查看结果

使用SpringDATA JPA条件并连表查询_第1张图片

Spring DATA JPA 一个连表查询dome就到这了

你可能感兴趣的:(使用SpringDATA JPA条件并连表查询)