溫馨提示×

springboot怎么批量新增數據

小億
235
2024-01-11 15:34:23
欄目: 編程語言

在Spring Boot中,可以使用JPA和Hibernate來批量新增數據。

首先,確保已經配置了JPA和Hibernate依賴項。然后,創建一個實體類,表示待新增的數據:

@Entity
@Table(name = "your_table")
public class YourEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    
    // getters and setters
}

接下來,創建一個Repository接口,用于操作數據庫:

@Repository
public interface YourRepository extends JpaRepository<YourEntity, Long> {
}

然后,在你的Service類中,注入YourRepository,并編寫批量新增的方法:

@Service
public class YourService {
    @Autowired
    private YourRepository yourRepository;
    
    public void batchSave(List<YourEntity> entities) {
        yourRepository.saveAll(entities);
    }
}

最后,在你的Controller中,調用批量新增的方法:

@RestController
public class YourController {
    @Autowired
    private YourService yourService;
    
    @PostMapping("/batch")
    public void batchSave(@RequestBody List<YourEntity> entities) {
        yourService.batchSave(entities);
    }
}

現在,當發送POST請求到/batch接口時,傳遞一個包含待新增數據的JSON數組,Spring Boot將會自動將數據保存到數據庫中。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女