How can Spring Boot bulk insert data?
In Spring Boot, you can use JPA and Hibernate to bulk insert data.
Firstly, make sure that the JPA and Hibernate dependencies are already configured. Next, create an entity class to represent the data to be added.
@Entity
@Table(name = "your_table")
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}
Next, create a Repository interface for interacting with the database.
@Repository
public interface YourRepository extends JpaRepository<YourEntity, Long> {
}
Next, in your Service class, inject YourRepository and write a method for batch adding.
@Service
public class YourService {
@Autowired
private YourRepository yourRepository;
public void batchSave(List<YourEntity> entities) {
yourRepository.saveAll(entities);
}
}
Finally, call the method for batch adding in your Controller.
@RestController
public class YourController {
@Autowired
private YourService yourService;
@PostMapping("/batch")
public void batchSave(@RequestBody List<YourEntity> entities) {
yourService.batchSave(entities);
}
}
Now, when sending a POST request to the /batch endpoint with a JSON array containing the data to be added, Spring Boot will automatically save the data to the database.