I use Hibernate to create relations as shown below. As far as I remember, there was no need to set FK fields as required, but I am not sure if it is the case for Hibernate or JPA.
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@EqualsAndHashCode.Exclude
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
}
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 20)
private String firstName;
@Column(nullable = false, length = 20)
private String lastName;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Comment> comments = new HashSet<>();
public void addComment(Comment comment) {
comments.add(comment);
comment.setUser(this);
}
public void removeComment(Comment comment) {
comments.remove(comment);
comment.setUser(null);
}
}
1- So, should I make userId field required?
2- For this kind of scenarios, I retrieve the entity using its id and then add this entity to the related entity before persist. For example, when I create a Comment, I check if the user by the given id exists and then add the returned user to the Comment entity before save. Is it a bad approach? Because we can also set comment.userId
field before persist without retrieving from database. Which one is better?