How many times the database got into Spring DATA JPA save (Iterable <S> entities)
I have the following lines of code:
@RequestMapping(value="/persons",method = RequestMethod.POST) @ResponseBody public ResponseEntity<List<Person>> saveUsers(@RequestBody List<Person> persons) { persons = (List<Person>) userRepository.save(persons); return new ResponseEntity<List<Person>>(persons, HttpStatus.OK); } And here is the repository:
@Transactional public interface UserRepository extends UserBaseRepository<User> { } @NoRepositoryBean public interface UserBaseRepository<T extends User> extends CrudRepository<T, Long> { public T findByEmail(String email); } It is working fine. When I run the code, I see the following logs.
Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person') Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person') Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person') Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person') It seems to be in DataBase 4 times. I saw an implementation of the save (iterable e) method, where the for loop starts to save each object. So my questions are:
- DB bit 4 times?
- if so, can this be done with 1 dB removal (using Spring Data JPA)? Doing this will improve performance when inserting a large number of records?
Yes, you request data four times.
You can paste in one batch statement by doing Hibernate Batching . In particular, take a look at doing batch inserts . Using batch inserts, you must manage the session manually by making explicit calls to the flush() and clear() methods in the session.
Also, consider setting the appropriate Hibernate Batching Properties , such as batch size (default is 5), and, if applicable, permission for Hibernate to reorder inserts and updates before constructing package statements:
hibernate.jdbc.batch_size = 25 hibernate.order_inserts = true hibernate.order_updates = true From docs to Hibernate Batching :
Hibernate disables JDBC-level batch loading transparently if you use an identity generator.
So, if Person uses an Identity generator (as opposed to a Sequence generator or TABLE generator), batch processing will not be performed. See this section for more details on why this is so.