user9381327
user9381327

Reputation: 11

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

Upvotes: 0

Views: 142

Answers (2)

Vasily Komarov
Vasily Komarov

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

songzeyang
songzeyang

Reputation: 41

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

Upvotes: 1

Related Questions