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 runs fine. While running 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 that, the DataBase is hit 4 times. I have seen the implementation of save(iterable e) method, where the for loop is run to save each entity. So, my questions is:
Yes, you are querying the data four times.
You can have the insertion done in one batch statement by implementing Hibernate Batching . In particular, take a look at performing batch inserts . Using batch inserts, you must control 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 the batch size (default 5), and if applicable, permission for Hibernate to re-order insertions and updates before constructing the batch statements:
hibernate.jdbc.batch_size = 25
hibernate.order_inserts = true
hibernate.order_updates = true
From the docs on Hibernate Batching :
Hibernate disables insert batching at the JDBC level transparently if you use an identity identifier generator.
So, if Person
is using an Identity
generator (as opposed to the Sequence
generator or TABLE
generator) batching won't take place. See this section for more details on why that is so.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.