6
The scenario is as follows: A user may have many or no comments in the newsletters posted on a system - obviously, a comment belongs to a single user.
The problem is that Hibernate does not have any annotations of the type @OneToZero
or anything like that, so how can I do this mapping?
On the user’s side (class User
), to list the comments a user has made the following:
@OneToMany(mappedBy = "userID", cascade = CascadeType.ALL)
private List<Comment> comments;
I think the above mapping is correct. But on the comments side (class Comment
) i don’t know what to do to define that a comment can exist in the same way that it can never be realized.
// como mapear aqui?
@JoinColumn(name = "fk_user")
private User userID;
I even tried to do with @ManyToOne
, but a NullPointerException
whenever I try to perform any CRUD operation with the user. A simple Insert is already enough to "crash" the application precisely because the comments are null. But there it is, a user has no comments when this is registered in the system.
My classes are like this:
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "userID", cascade = CascadeType.ALL)
private List<Comment> comments;
/* ...outros atributos... */
}
@Entity
@Table(name = "comments")
public class Comment implements Serializable {
@Id
@GeneratedValue
private Long id;
@ManyToOne //ManyToOne gera uma NullPointerException, mas creio que esteja próximo do certo
@JoinColumn(name = "fk_user")
private User userID;
/* ...outros atributos... */
}
If you have a Nullpointerexception when recording Comment, then you are recording Comment! Why do you try to record Comment without a user? A "one to zero" link would be the same as no connection, so this type of link would not make sense. As long as you’re not trying to record one Comment without a User, your annotations are correct and should work record user without any comment.
– Caffé
@Caffe magically worked today when I went to test the same code, including using the same Insert.
– Renan Gomes