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
.