溫馨提示×

springboot怎么批量新增數(shù)據(jù)

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

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

首先,確保已經(jīng)配置了JPA和Hibernate依賴項(xiàng)。然后,創(chuàng)建一個(gè)實(shí)體類,表示待新增的數(shù)據(jù):

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

接下來,創(chuàng)建一個(gè)Repository接口,用于操作數(shù)據(jù)庫:

@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中,調(diào)用批量新增的方法:

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

現(xiàn)在,當(dāng)發(fā)送POST請求到/batch接口時(shí),傳遞一個(gè)包含待新增數(shù)據(jù)的JSON數(shù)組,Spring Boot將會自動將數(shù)據(jù)保存到數(shù)據(jù)庫中。

0