Spring JpaRepositroy.save() does not appear to throw exception on duplicate saves

后端 未结 4 1837
遇见更好的自我
遇见更好的自我 2020-12-09 02:36

I\'m currently playing around on Spring boot 1.4.2 in which I\'ve pulled in Spring-boot-starter-web and Spring-boot-starter-jpa.

My main issue is that when I save a

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 03:27

    To build upon Shazins answer and to clarify. the CrudRepositroy.save() or JpaRespository.saveAndFlush() both delegate to the following method

    SimpleJpaRepository.java

    @Transactional
    public  S save(S entity) {
    
        if (entityInformation.isNew(entity)) {
            em.persist(entity);
            return entity;
        } else {
            return em.merge(entity);
        }
    }
    

    Hence if a user tries to create a new entity that so happens to have the same id as an existing entity Spring data will just update that entity.

    To achieve what I originally wanted the only thing I could find was to drop back down to JPA solely, that is

    @Transactional
    @PostMapping("/createProduct")
    public Product createProduct(@RequestBody @Valid Product product) {
        try {
            entityManager.persist(product);
            entityManager.flush();
        }catch (RuntimeException ex) {
            System.err.println(ex.getCause().getMessage());
        }
    
        return product;
    }
    

    Here if we try to persist and new entity with an id already existing in the database it will throw will throw the constraint violation exception as we originally wanted.

提交回复
热议问题