springboot简单增删改查代码
时间: 2023-10-14 13:20:14 浏览: 89
以下是一个简单的基于Spring Boot的增删改查代码示例:
1. 创建实体类
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getters and setters
}
```
2. 创建数据访问接口
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
3. 创建服务类
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
public User addUser(User user) {
return userRepository.save(user);
}
public User updateUser(Long id, User user) {
User existingUser = userRepository.findById(id).orElse(null);
if (existingUser != null) {
existingUser.setName(user.getName());
existingUser.setEmail(user.getEmail());
userRepository.save(existingUser);
}
return existingUser;
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
```
4. 创建控制器类
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("")
public User addUser(@RequestBody User user) {
return userService.addUser(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.updateUser(id, user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
```
以上代码实现了一个简单的增删改查功能,你可以在控制器类的接口上添加相应的注解来限制访问权限。同时,你可以添加异常处理程序来处理异常情况。
阅读全文