0

I have an entity Employee. For example: I have saved few records into database like below:

employeeRepository.save(employees);

In next request, I would like to update few saved entities and delete few saved entities and create few entities newly.

Please let me know the easy way to do it in Spring data JPA.

Krish
  • 1,804
  • 7
  • 37
  • 65

2 Answers2

0

Instantiate and Use EmployeeRepository To instantiate our EmployeeRepository that has extended CrudRepository, we can use dependency injection.

public class EmployeeService {
    @Autowired    
    private EmployeeRepository employeeRepository;
    Employee saveEmployee(Employee employee){
    employeeRepository.save(employee);  
    }
    List<Employee> saveEmployee(List<Employee> employees){
        for(Employee employee:employees){
            saveEmployee(employee);         }   
    } 
    void deleteEmployee(Employee employee){
        employeeRepository.delete(employee);
    }
    void deleteEmployee(List<Employee> employees){
        for(Employee employee:employees){
            deleteEmployee(employee);
        }
    } 
}

Now we are ready to use methods of CrudRepository. Find the example for some of its methods.

  1. Create and Update one entity:

Employee savedEmployee = employeeRepository.save(employee);

  1. Delete one entity::

employeeRepository.delete(employee);

If you perform bulk operation then you can override saveEmployee() and deleteEmployee() on EmployeeService class.

Hardik
  • 1,519
  • 1
  • 10
  • 10
0

You mainly want to derive on Spring Data JPAs derived query features as much as possible! You definitely don't want to write your own boilerplate code because that defeats the purpose of Spring Data JPA entirely!

Delete

The best (and cleanest) way to do this is to let Spring Data JPA derive the query for you:

public interface EmployeeRepository extends CrudRepository<Employee, Long> {

    Long deleteByIdIn(List<Long> employeeIdsToDelete);

}

See this answer.

Update

Updates can be done this way:

@Modifying
@Query("update Employee empl set empl.param =:param where empl.id =:emplId")
void updateEmployees(@Param("emplId") Long emplId, @Param("param") paramValue);

And otherwise can be done with a combination of find and modify (likely in the Service method:

public void myEmployeeServiceUpdateMethod(List<Long> emplIds) {
    List<Employee> employees = employeeRepository.findByIdIn(emplIds);
    employees.forEach(empl -> empl.setParam("NewParam!");
}

And Spring JPA will automatically flush and update those values for you!

See this answer.

Create

Creates you're already doing right. Just pass in the list of new entities to #save.

Dovmo
  • 8,121
  • 3
  • 30
  • 44