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));
testRepository.saveAll(testRepository);

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

2 Answers

1
Adrian On

autowire EntityManager, detach entity and set id to null

sampleList.forEach(i -> {
   entityManager.detach(i);
   i.setId(null);
   i.setSomeValue(1234);
});

and then save the list with the same repository

1
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()
    .map(SampleClass::new)
    .collect(Collectors.toList);;
copyList.forEach(i -> i.setSomeValue(1234));
testRepository.saveAll(copyList);