插入数据库需要很长时间,如何加快整个过程?在项目中,我使用的是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);
}
最佳答案
意见:
- 不要在“for”语句中创建新的 person 对象
- 不要在“for”语句中启动新事务
原因:
- 在for语句中new对象会造成资源浪费
- SQL尝试放在一个stansaction中,减少对数据库的操作
关于java - hibernate加速插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51837446/