springboot进行增删改查操作代码
时间: 2023-10-13 15:12:04 浏览: 79
下面是一个使用Spring Boot进行增删改查操作的示例代码:
1. 创建一个实体类
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
// 省略getter/setter方法
}
```
2. 创建一个repository
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
3. 创建一个service
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> findAll() {
return userRepository.findAll();
}
public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new NotFoundException("User not found with id " + id));
}
public User save(User user) {
return userRepository.save(user);
}
public void deleteById(Long id) {
userRepository.deleteById(id);
}
public User update(Long id, User updatedUser) {
User user = userRepository.findById(id)
.orElseThrow(() -> new NotFoundException("User not found with id " + id));
user.setName(updatedUser.getName());
user.setAge(updatedUser.getAge());
return userRepository.save(user);
}
}
```
4. 创建一个controller
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("")
public List<User> findAll() {
return userService.findAll();
}
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping("")
public User create(@RequestBody User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id) {
userService.deleteById(id);
}
}
```
这样就完成了一个简单的增删改查操作的代码示例。
阅读全文