CrudRepository and Hibernate: save(List) vs save(Entity) in transaction

后端 未结 3 672
渐次进展
渐次进展 2020-12-14 06:54

Would it make any difference if I do:

@Transactional
public void processData() {
    List entities = ....;
    MyEntityRepository.save(entiti         


        
相关标签:
3条回答
  • 2020-12-14 07:25

    From SimpleJpaRepository:

    @Transactional
    public <S extends T> List<S> More save(Iterable<S> entities) {
    
        List<S> result = new ArrayList<S>();
    
        if (entities == null) {
            return result;
        }
    
        for (S entity : entities) {
            result.add(save(entity));
        }
    
        return result;
    }
    

    So, your second business method only shadows save(Iterable<S> entities) Crud Repository method, in the sense that it iterates the list and calls save(S) on your behalf.

    As long as transaction is demarcated from your processData business method, there is no really a difference in performance or queries executed.

    0 讨论(0)
  • 2020-12-14 07:36

    For SpringData Jpa, a cleaner approach will be to use repository.saveAll instead of a forloop with repository.save. saveAll will automatically iterate through the list and save it.

    saveAll is a part of JpaRepository, so no need to define any method.

    0 讨论(0)
  • 2020-12-14 07:46

    As what has been mentioned by Ori Dar, there is no really a difference.

    However, there is one thing you should notice:the method used to a save a list of elements has been renamed into <S extends T> List<S> saveAll(Iterable<S> entities) in 2.2.0.M1 according to the repo history, and the save method no longer takes as argument a list.

    Since I don't have 50 reputation to comment the answer or question above, I have to write a new answer about this change.

    0 讨论(0)
提交回复
热议问题