用springboot写增删改查功能
时间: 2023-06-30 10:03:15 浏览: 70
好的,下面是一个简单的示例:
1. 创建一个实体类
```
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
// getter/setter 省略
}
```
2. 创建一个 DAO 层接口
```
public interface UserRepository extends JpaRepository<User, Long> {
}
```
3. 创建一个 Service 层接口
```
public interface UserService {
List<User> findAll();
User findById(Long id);
void save(User user);
void deleteById(Long id);
}
```
4. 实现 Service 层接口
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public User findById(Long id) {
return userRepository.findById(id).orElse(null);
}
@Override
public void save(User user) {
userRepository.save(user);
}
@Override
public void deleteById(Long id) {
userRepository.deleteById(id);
}
}
```
5. 创建一个 Controller 类
```
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("")
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping("")
public void createUser(@RequestBody User user) {
userService.save(user);
}
@PutMapping("/{id}")
public void updateUser(@PathVariable Long id, @RequestBody User user) {
User oldUser = userService.findById(id);
if (oldUser != null) {
oldUser.setName(user.getName());
oldUser.setAge(user.getAge());
userService.save(oldUser);
}
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteById(id);
}
}
```
6. 启动应用程序,使用 Postman 或其他工具测试增删改查功能。
阅读全文