简体   繁体   中英

JPA insert rows in multiple transaction, limit the maximum row numbers in a single transaction

I would like to insert every 1000 row in a separate transaction. So if there are 3000 row than it should insert it in 3 different transaction. I don't use Spring.

import com.company.UserDAO;
import javax.inject.Inject;
import javax.transaction.Transactional;

public class Round{

    UserDAO userDao;

    @Inject 
    public Round(UserDAO userDao){
        this.userDao = userDao;
    }


    @Transactional
    @Scheduled(every = "10s")
    void schedule() {

        Synchronization synchronization = new Synchronization();
        synchronization.setUserDAO( userDao );

        synchronization.synchronize();
    }

}


public class Synchronization{

    UserDAO userDao;


    public void synchronize(){

        List<User> newUsers = Arrays.asList( new User(a1), new User(a2), ..., new User(a170.000);

        for( User user : newUsers){
            saveCreate( user )
        }

    }

    saveCreate(User user){
        userDao.create(user);
        // which is calling somewhere the: getEntityManager().persist(entity);
    }
}

How can I create new transaction for every 1000 row?

1, Flush and clear the entityManager at every 1000 row. Will it create a new transaction?

int i = 0;
for( User user : newUsers){
saveCreate( user )
i++;

    if( i % 1000 == 0 ){
        userDao.getEntityManager.flush();
        userDao.getEntityManager.clear();
    }
}

2, Make the saveCreate method @Transactional, instead of the schedule()?

3, create new class, with new method which is annotated with @Transactional, and create new intance from it, when there are more than 1000 row?

Transaction tr = new Transaction;
int i = 0;
for( User user : newUsers){
    i++;
    tr.singleTransaction( user );
    if( i % 1000 == 0 ){
        tr = = new Transaction;
    }
}

public class Transaction{

    @Transactional
    public void singleTransaction( User user){
        saveCreate( user );
    }
}

4, something else?

Thank you in advance!

Write a method which will insert 1000 records and mark it as @Transactional(propagation = Propagation.REQUIRES_NEW)

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveData(List<Object> data)..

Then, call that method few times, whenever the method is called, new transaction will be created.

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