基于Mysql数据库,使用springboot写一个增删改查后端接口
时间: 2023-03-21 12:01:59 浏览: 170
基于springboot实现的增删改查
5星 · 资源好评率100%
好的,下面是一个使用Spring Boot框架和MySQL数据库的增删改查后端接口的示例代码:
1. 配置pom.xml文件,添加MySQL和Spring Boot Web依赖:
```
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
```
2. 配置application.properties文件,设置MySQL数据库连接信息:
```
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 创建一个实体类User,用于映射数据库表的数据结构:
```
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 省略 getter 和 setter 方法
}
```
4. 创建一个接口UserRepository,用于继承JpaRepository接口,实现对User实体类的CRUD操作:
```
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
5. 创建一个控制器UserController,用于实现对User实体类的CRUD操作:
```
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("")
public List<User> getAllUsers() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
Optional<User> optionalUser = userRepository.findById(id);
return optionalUser.map(user -> ResponseEntity.ok().body(user)).orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping("")
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
Optional<User> optionalUser = userRepository.findById(id);
if (optionalUser.isPresent()) {
User existingUser = optionalUser.get();
existingUser.setName(user.getName());
existingUser.setEmail(user.getEmail());
userRepository.save(existingUser);
return ResponseEntity.ok().body(existingUser);
} else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
return ResponseEntity.noContent().build();
}
}
```
以上就是一个使用Spring Boot框架和MySQL数据库的增删改查后端接口的示例代码。
阅读全文