Reputation: 11
Insert to the database takes to much time, how to speed up the whole process? In the project, I'm using hibernate
for (int a = 0; a < persons.size(); a++) {
Person person = new Person();
Gender gender = new Gender();
gender.setName(persons.get(a).getGender());
gender = genderRepository.save(gender);
Country country = new Country();
country.setName(persons.get(a).getCountry());
country = countryRepository.save(country);
person.setName(personss.get(a).getFirstName());
person.setLastName(persons.get(a).getLastName());
person.setAdditionalInfo(persons.get(a).getIdentifier());
person.setGender(gender);
Set<Country> countries = new HashSet();
countries.add(country);
person.setCountries(countries);
personRepository.save(person);
}
Upvotes: 0
Views: 142
Reputation: 1425
You need to execute all insert operations in the one hibernate transaction. Create a method addPersonList in your Person repository
@Autowired
private EntityManager em;
@Transactional
public void addPersonList(){
for (Person personFromList : persons) {
Person person = new Person();
Gender gender = new Gender();
gender.setName(personFromList.getGender());
em.persist(gender);
Country country = new Country();
country.setName(personFromList.getCountry());
em.persist(country);
person.setName(personFromList.getFirstName());
person.setLastName(personFromList.getLastName());
person.setAdditionalInfo(personFromList.getIdentifier());
person.setGender(gender);
Set<Country> countries = new HashSet();
countries.add(country);
person.setCountries(countries);
em.persist(person);
}
}
Now, all operations are in one PersistContext and hibernate can optimize inserts and commits in the database.
UPD:
If you have not changed the transaction propagation level (default propagation level is Propagation.REQUIRED) you can use other repositories @Transactional methods in addPersonList method - it will not harm the speed because hibernate will not create new transactions for them. So, this code is OK too:
Gender gender = new Gender();
gender.setName(personFromList.getGender());
gender = genderRepository.save(gender);
Upvotes: 1
Reputation: 41
opinion:
cause:
Upvotes: 1