I fetch a list of objects using CrudRepository object for my entity class. I want to duplicate the list in database with some field for every Object in the list modified. How do I achieve it with same repository object?

The sample code is as follows. It modifies the existing rows in Database. I want it to append the modifications as new rows in the database.

@Autowired TestRepository testRepository;

List<SampleClass> sampleList = testRepository.findAllBySomeId(id);
sampleList.forEach(i -> i.setSomeValue(1234));

Do I need to make separate Repository object? Is it possible with same Repository object annotated with @Autowired?

2 Answers

Adrian On

autowire EntityManager, detach entity and set id to null

sampleList.forEach(i -> {

and then save the list with the same repository

Golov Pavel On

For example, you can create a copy constructor in the SampleClass (don't copy id field). After that you should copy all the objects received from DB and save their to DB. You can do it like this:

List<SampleClass> copyList = testRepository.findAllBySomeId(id).stream()
copyList.forEach(i -> i.setSomeValue(1234));