admin管理员组文章数量:1350050
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
.
本文标签: hibernateSpring boot JPA manyToOne duplicate key already existsStack Overflow
版权声明:本文标题:hibernate - Spring boot JPA manyToOne duplicate key already exists - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743872002a2553642.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论