Moler
Moler

Reputation: 995

Saving to database inside loop

i wanted to insert some test data in my database, so i looped save method. But it only saves it 1 time. Can you explain why?

Here is my controller method with my loop:

@PostMapping("")
public Long save(@RequestBody Car car) {
    for (int i = 0; i < 100; i++) {
        System.out.println("??");
        carService.save(car);
    }
    Car savedCar = carService.save(car);
    return savedCar.getId();
}

carService:

@Override
public Car save(Car car) {
    return carRepository.save(car);
}

carRepository:

public interface CarRepository extends CrudRepository<Car, Long> {
    List<Car> findAll();
    Car getCarById(Long id);
}

Upvotes: 0

Views: 1719

Answers (3)

NiVeR
NiVeR

Reputation: 9796

It saves it 1 time because you are saving 100 times the same Car object. No changes are detected and there is no need to refresh the persistent state of the object.

Before the first save operation, the car instance is just a value object, in the sense that, it has not yet a persistent state. This means that there is no id is associated to the value object. After the first save is done, car now has an identifier associated with it. At each consecutive save this id is used to identify the object, as no changes are done, it is not necessary to perform any changes in the database.

Upvotes: 4

Allan Braga
Allan Braga

Reputation: 470

When you save in database using Hibernate passing the referency object automatically the id is setted in the object, so when you save again it´s only editing the object. If you want so save change the id to 0.

@PostMapping("")
public Long save(@RequestBody Car car) {
  for (int i = 0; i < 100; i++) {
         System.out.println("??");
         car.setId(0);
         carService.save(car);
    }
    Car savedCar = carService.save(car);
    return savedCar.getId();
  }

Upvotes: 0

Ishant Gaurav
Ishant Gaurav

Reputation: 1203

Because the save method of Spring data -jpa is to save and update for both . Once you save the data it save it in db properly by creating new row , but second time you again save the same data . Spring-data-jpa finds the same data so it just update the same row and do no create new row

Upvotes: 1

Related Questions