Update or SaveorUpdate in CRUDRespository, Is there any options available

前端 未结 2 1671
名媛妹妹
名媛妹妹 2020-12-02 18:46

I am trying to do CRUD operations with My Entity bean. CRUDRepository provide standard methods to find, delete and save b

相关标签:
2条回答
  • 2020-12-02 18:52

    The issue is "i am using thymeleaf UI template and The Bean that i am trying to persist that is Form bean not Entity bean and that's why Spring boot is not saving it. Now i have to convert the entire Form bean into Entity bean with changed values and try to persist it." I got the solution for the specific problem i faced in my project, The solution is use @ModelAttribute to convert the form bean to entity.

    @ModelAttribute("spaceSummary")
    public SpaceSummary getSpaceSummary(int id){
        return this.spaceSummaryService.getSpaceSummary(id);
    }
    

    and

    @RequestMapping(value="/mgr/editSpace", method = RequestMethod.POST)
    public ModelAndView editSpace(@ModelAttribute("spaceSummary") SpaceSummary                
    spaceSummary, BindingResult result, RedirectAttributes redirect, ModelAndView model) {
    
    }
    
    0 讨论(0)
  • 2020-12-02 18:56

    The implementation of the method

    <S extends T> S save(S entity)

    from interface

    CrudRepository<T, ID extends Serializable> extends Repository<T, ID>

    automatically does what you want. If the entity is new it will call persist on the entity manager, otherwise it will call merge

    The code looks like this:

    public <S extends T> S save(S entity) {
    
        if (entityInformation.isNew(entity)) {
            em.persist(entity);
            return entity;
        } else {
            return em.merge(entity);
        }
    }
    

    and can be found here. Note that SimpleJpaRepository is the class that automatically implements CrudRepository in Spring Data JPA.

    Therefore, there is no need to supply a custom saveOrUpdate() method. Spring Data JPA has you covered.

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