最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

hibernate - Spring boot JPA manyToOne duplicate key already exists - Stack Overflow

programmeradmin3浏览0评论

I am trying to get a manyToOne unidirectional relationship working, but i cant seem to get it to work

@Entity
@Table(name = "comments")
@Data
@AllArgsConstructor
public class Comments {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}, fetch = FetchType.LAZY)
    @JoinColumn(name="user_id", referencedColumnName = "id", nullable = false)
    private User user;
}


@Entity
@Table(name = "user")
@Data
@AllArgsConstructor
public class User {
    @Id
    private String id;

    @Column(nullable = false)
    private String name;

}

What i try to do is the following, I create a new comment and a new user, it works fine

var user = userRepo.findById("userId1").orElse(User.builder().id("userId1").build());

final var comment = Comment.builder()
        .user(user).build();

commentRepo.save(comment); // this works, both are new objects/rows

But if i then try and add do the following, it falls over

var existingUser = userRepo.findById("userId1").orElse(User.builder().id("userId1").build());

final var comment1 = Comment.builder()
        .user(existingUser).build();

commentRepo.save(comment1); // this falls over

So im adding a new comment to an existing user... and it doesnt like it

Caused by: .postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "user_id_pkey"
  Detail: Key (id)=(userId1) already exists

.

发布评论

评论列表(0)

  1. 暂无评论