How to save same object multiple times use Spring Data?

Viewed 7733

I want save an object multiple times, the code below can not work:

for(int i = 0; i < 5; i++) {
    repository.save(object);
}

Then I change the source to:

List<SomeObject> objectList = new ArrayList<>();
for(int i = 0; i < 5; i++) {
    objectList.add(object);
}
repository.save(object);

But it also can not work, It only save the object one time to database.

Maybe because it point to one instance, but I want to know if there is an easy way to save an object multiple times?

Thank you!

3 Answers

It saves only 1 time the object because you are using the same instance every times.

So the first time you use object, so now it has an ID, then you use object again, but as we said it has an id so instead to save it, yours program update it inside you db.

For example if you do this:

for(int i = 0; i < 5; i++) {
    repository.save(new Object());
}

Or if you have a list of Objects, like

List<SomeObject> objectList = new ArrayList<>();
for(int i = 0; i < 5; i++) {
    objectList.add(object);
}

you could do this:

repository.saveAll(objectList);

Now you find 5 rows inside your table

I am not familiar with Spring data and might misunderstand the problem but generally there is no point to save the same object many times.

You need to explicitly create a clone/copy (or so) of an instance and save all these instances separately if you need multiple instances in database.

For example add creating new instance in a loop that saves the object.

Using the constructor, you can save same object multiple time:

Repository.save(new object(String name,String age));
Related