Question:
The scenario is as follows: A user may have many or no comments in the bulletins posted on a system – obviously, a comment belongs to a single user.
The problem is that Hibernate doesn't have any annotations like @OneToZero
or anything similar, so how can I do this mapping?
On the user's side ( User
class), to list the comments that a user has, I did the following:
@OneToMany(mappedBy = "userID", cascade = CascadeType.ALL)
private List<Comment> comments;
I believe the above mapping is correct. But on the comments side ( Comment
class) 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 doing it with @ManyToOne
, but I @ManyToOne
a NullPointerException
whenever I try to perform any CRUD operation with the user. A simple insert is enough to " crash " the application precisely because the comments are null. But there you have it, a user has no comments when he is registered in the system.
My classes look 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... */
}
Answer:
Try adding the @NotFound
annotation with the attribute (action=NotFoundAction.IGNORE)
, leaving:
@Entity
@Table(name = "comments")
public class Comment implements Serializable {
@Id
@GeneratedValue
private Long id;
@NotFound(action=NotFoundAction.IGNORE) //Linha inserida
@JoinColumn(name = "fk_user")
private User userID;
/* ...outros atributos... */
}
Sources:
- https://stackoverflow.com/questions/841354/
- https://stackoverflow.com/questions/7146064/
- http://www.concretepage.com/hibernate/example-notfound-hibernate