简体   繁体   中英

hibernate speed up insert

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);
}

opinion:

  1. Don't be in "for" statement new person object
  2. Don't be in "for" statement start new transaction

cause:

  1. In "for" statement new object will cause wasting of resources
  2. SQL try put in one stansaction ,Reduce operations on the database

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM