用springboot写一个条件查询
时间: 2024-03-09 20:18:18 浏览: 94
基于springboot的教务查询系统源码
假设要查询一个学生表,根据不同的条件查询不同的结果,可以按照以下步骤进行:
1. 定义实体类
```java
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer age;
private String gender;
// getter/setter方法省略
}
```
2. 定义Repository接口
```java
@Repository
public interface StudentRepository extends JpaRepository<Student, Integer>, JpaSpecificationExecutor<Student> {
}
```
3. 定义查询条件
```java
public class StudentSpecification {
public static Specification<Student> nameLike(String name) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.like(root.get("name"), "%" + name + "%");
}
public static Specification<Student> ageGreaterThanOrEqualTo(Integer age) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.greaterThanOrEqualTo(root.get("age"), age);
}
public static Specification<Student> genderEqual(String gender) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("gender"), gender);
}
}
```
4. 编写Controller层代码
```java
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@GetMapping
public List<Student> query(@RequestParam(required = false) String name,
@RequestParam(required = false) Integer age,
@RequestParam(required = false) String gender) {
Specification<Student> specification = Specification.where(null);
if (StringUtils.isNotBlank(name)) {
specification = specification.and(StudentSpecification.nameLike(name));
}
if (age != null) {
specification = specification.and(StudentSpecification.ageGreaterThanOrEqualTo(age));
}
if (StringUtils.isNotBlank(gender)) {
specification = specification.and(StudentSpecification.genderEqual(gender));
}
return studentRepository.findAll(specification);
}
}
```
以上代码实现了根据不同的条件查询不同的结果,当查询条件为空时返回所有的结果。可以通过访问`http://localhost:8080/students?name=张三&age=18&gender=男`来获取符合条件的学生信息。
阅读全文