SpringBoot+ Bean Seracher + mysql使用
步骤如下:
- 创建一个SpringBoot项目,在pom.xml中添加MySQL和Bean Searcher的依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>bean-searcher-spring-boot-starter</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
</dependencies>
- 在application.properties中配置MySQL数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 创建一个实体类User:
@Entity
@Table(name = "user")
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
}
- 创建一个Repository接口UserRepository:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
- 创建一个Controller类UserController:
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("")
public List<User> findAll(@SearchParam Specification<User> specification) {
return userRepository.findAll(specification);
}
@PostMapping("")
public User save(@RequestBody User user) {
return userRepository.save(user);
}
}
- 启动项目,在浏览器中访问http://localhost:8080/users,可以看到返回的用户列表。在浏览器中访问http://localhost:8080/users?name_like=Tom&age=20,可以看到返回的名字包含Tom并且年龄是20的用户列表。如果要使用更多的查询条件,请参考Bean Searcher的文档
原文地址: https://www.cveoy.top/t/topic/fgUo 著作权归作者所有。请勿转载和采集!