Vinay Pandey
Vinay Pandey

Reputation: 451

Calling Save() after findAll() in JPA repository

I am working on an SpringBoot Project and Using the Spring JPA. I have scenario where I need to fetch all the records and then update them after modification. For example

 @Entity
 @Table(name="Employee")
 public class Employee{
   
   @ID
   @Column(name="ID")
   Long id;

   @Column(name="age")
   private  int age;
   
   @Column(name="name")
   private  String name;

   @Embedded
   private Address address

   //TODO getters and setters goes below
 }

and then in the repository

@Repository
public interface EmployeeRepository extends JPARepository<Employee, Long>{
}

and in the service Iam trying as below:

@Service
public class EmployeeService{
 
  @Autowired
  EmployeeRepository repository;

 @Transactional
 public void updateEmployee(){
     List<Employee> list = repository.findAll();
     for(Employee employee :list) {

      employee.setAge(employee.getAge()+4);
     
      repository.save(employee); //This is not working.
     }
  }
}

Save is neither working nor throwing any error.I have also tried saveAndFlush() but not working. Can someone please help me. I want my objects to get updated.

Upvotes: 1

Views: 1616

Answers (1)

Martin Lund
Martin Lund

Reputation: 1169

I tried to recreate your issue, but i cant reproduce your error.

Tried to replicate your issue here

My entities get updated with this perfectly fine.

After updates

You say you are doing more logic than this, have you tried printing out your entities after you have made the save, to see if something has been updated, and that it fails in another place in your code?

The code above for me updates all entities as expected :)


logging.level.org.hibernate.SQL=TRACE

Add this to application.properties / yaml file for more tracing of SQL statements

Upvotes: 1

Related Questions