springboot jpa实现多条件动态查询

一.问题描述:

使用jpa实现多条件分页动态查询用户数据。

二.代码部分

1.建立实体类代码

import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;

@Entity
@EntityListeners(AuditingEntityListener.class)
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String sex;

    private String phone;

    private Integer age;

    public User() {
    }

    public User(String name, String sex, String phone, Integer age) {
        this.name = name;
        this.sex = sex;
        this.phone = phone;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", phone='" + phone + '\'' +
                ", age=" + age +
                '}';
    }
}

2.jpa代码

import com.wyh.jpatest.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface UserRepository extends JpaRepository,  JpaSpecificationExecutor {
}

3.service接口和service实现类

接口代码:

mport com.wyh.jpatest.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface UserService {
    Page findByCondition(Integer page,  Integer size, String sex, Integer ageBegin, Integer ageEnd);
}

接口实现类代码:

import com.wyh.jpatest.dao.UserRepository;
import com.wyh.jpatest.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;


@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;


    @Override
    public Page findByCondition(Integer page,  Integer size, String sex, Integer ageBegin, Integer ageEnd) {
        Pageable pageable = PageRequest.of(page, size);
        return userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            List predicates = new ArrayList();

            if (!StringUtils.isEmpty(sex)){             //性别
                predicates.add(criteriaBuilder.equal(root.get("sex"),sex));
            }


            if (ageBegin != null){          //年龄大于ageBegin
                predicates.add(criteriaBuilder.greaterThan(root.get("age"),ageBegin));
            }

            if (ageEnd != null){            //年龄小于ageEnd
                predicates.add(criteriaBuilder.lessThan(root.get("age"),ageEnd));
            }

            return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        },pageable);
    }
}

4.controller层

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    //page表示页数,默认是第0页
    //size表示每页显示条数,默认显示10条
    @PostMapping
    public Object findByCondition(@RequestParam(value = "page", defaultValue = "0") Integer page,
                            @RequestParam(value = "size", defaultValue = "10") Integer size,
                            @RequestParam(value = "sex", defaultValue = "男") String sex,
                            @RequestParam(value = "ageBegin") Integer ageBegin,
                            @RequestParam(value = "ageEnd") Integer ageEnd){
         List list = userService.findByCondition(page, size, sex, ageBegin, ageEnd).getContent();
         Map map = new HashMap();
         map.put("num", list.size());
         map.put("listData", list);

         return map;
    }
}

5.application.properties配置代码

spring.datasource.url=jdbc:mysql://localhost:3306/jpa?characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2b8
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

三.项目结构和数据库

1.项目结构

springboot jpa实现多条件动态查询_第1张图片
项目结构图.png

2.数据库表

springboot jpa实现多条件动态查询_第2张图片
user表.png

四.测试

1.查询年龄大于14,小于30,性别为男的用户,并返回第0页的数据,每页显示设置为3条数据

springboot jpa实现多条件动态查询_第3张图片
test1.png

2.查询年龄大于13,性别为男的用户,并返回第1页的数据,每页显示设置为2条数据

springboot jpa实现多条件动态查询_第4张图片
test2.png

你可能感兴趣的:(springboot jpa实现多条件动态查询)