插入数据库要花费很多时间,如何加快整个过程?在项目中,我正在使用休眠
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);
}
答案 0 :(得分:1)
观点:
原因:
答案 1 :(得分:1)
您需要在一个休眠事务中执行所有插入操作。 在个人存储库中创建方法addPersonList
@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);
}
}
现在,所有操作都在一个PersistContext中,并且hibernate可以优化数据库中的插入和提交。
UPD:
如果您尚未更改事务传播级别(默认传播级别为Propagation.REQUIRED),则可以在addPersonList方法中使用其他存储库@Transactional方法-这不会影响速度,因为休眠不会为其创建新的事务。因此,此代码也可以:
Gender gender = new Gender();
gender.setName(personFromList.getGender());
gender = genderRepository.save(gender);