Spring JPA在检查是否存在类似记录后保存新实体

时间:2018-03-29 13:46:52

标签: java spring jpa

我在作者控制器中实现了 addAnAuthor() getAllAuthors()方法,我的get实现工作正常。但是,如果我尝试使用不存在的id添加,我会在邮递员中得到以下错误。尝试使用现有作者ID 的POST覆盖现有记录并获取创建的响应代码201:

"message": "could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"

我的添加作者实施代码是:

    public class AuthorService {
        @Autowired
        private AuthorRepository authorRepository;

    public String addAuthor(Author author) {
            if(authorRepository.existsByFirstName(author.getFirstName())){
                System.out.println("checked exists");
                return "Already Exists";
            }

            else{
                authorRepository.save(author);
                return "Created";
            }


        }
}

在我的存储库中我有这个方法:

boolean existsByFirstName(String firstName);

作者实体代码是:

@Entity
@Table(name = "Author")
public class Author {
@Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @NotNull
    @Size(max = 100)
    private String firstName;

    @NotNull
    @Size(max = 100)
    private String lastName;

    @JsonManagedReference
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "author")
    private Set<Book> books = new HashSet<>();

    protected Author() {}
}

1 个答案:

答案 0 :(得分:0)

确保使用数据库

中的主键创建了自动增量ID