SpringBoot+ Bean Seracher + mysql使用带条件查询
要在SpringBoot中使用BeanSeracher和MySQL进行带条件查询,可以按照以下步骤:
- 首先,在pom.xml中添加以下依赖:
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- 在实体类中定义需要查询的属性,并在Repository接口中继承JpaSpecificationExecutor接口:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
private String email;
// getter/setter省略
}
@Repository
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
- 在Controller中定义查询接口,并使用BeanSeracher构造查询条件:
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/search")
public List<User> search(@RequestParam(required = false) String name,
@RequestParam(required = false) Integer age,
@RequestParam(required = false) String email) {
Specification<User> specification = (root, query, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
if (name != null) {
predicates.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
}
if (age != null) {
predicates.add(criteriaBuilder.equal(root.get("age"), age));
}
if (email != null) {
predicates.add(criteriaBuilder.equal(root.get("email"), email));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
};
return userRepository.findAll(specification);
}
}
- 使用Postman等工具测试查询接口,可以按照name、age、email等属性进行查询。例如:
GET http://localhost:8080/users/search?name=Tom&age=20
以上就是使用SpringBoot+ Bean Seracher + mysql实现带条件查询的步骤
原文地址: https://www.cveoy.top/t/topic/fgUy 著作权归作者所有。请勿转载和采集!