封装一个springboot的批量新增
时间: 2023-09-22 08:11:00 浏览: 89
以下是一个基本的Spring Boot批量插入的示例:
1.创建一个实体类,例如User:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private int age;
// getters and setters
}
```
2.创建一个UserRepository接口扩展JpaRepository:
```java
public interface UserRepository extends JpaRepository<User, Long> {
}
```
3.编写一个UserService类:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void batchSave(List<User> userList) {
userRepository.saveAll(userList);
}
}
```
4.在你的控制器中注入UserService类:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/users")
public void batchSaveUsers(@RequestBody List<User> userList) {
userService.batchSave(userList);
}
}
```
5.现在你可以使用POST请求将数据发送到/users端点进行批量插入了:
```bash
curl -X POST -H "Content-Type: application/json" -d '[{"name": "User1", "age": 20}, {"name": "User2", "age": 30}]' http://localhost:8080/users
```
阅读全文