How to implement a "one to zero" mapping?

6

The scenario is as follows: A user can have many or no comments on bulletins published on a system - obviously, a comment belongs to a single user.

The problem is that Hibernate has no annotations of type @OneToZero or something similar, so how do I do this mapping?

On the user side (class User ), to list the comments that a user has made I did the following:

@OneToMany(mappedBy = "userID", cascade = CascadeType.ALL)
private List<Comment> comments;

I think the mapping above is correct. But on the side of comments (class Comment ) I do not know what to do to define that a comment can exist in the same way that it can never be performed.

// como mapear aqui? 
@JoinColumn(name = "fk_user")
private User userID;

I even tried to @ManyToOne , but a NullPointerException is thrown whenever I try to perform any CRUD operation with the user. A simple insert is enough to "crash" the application just because the comments are null. But there it is, a user has no comments when logged in.

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... */
}
    
asked by anonymous 12.05.2015 / 19:24

1 answer

1

Try to add the annotation @NotFound with the (action=NotFoundAction.IGNORE) attribute, getting:

@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:

  • link
  • link
  • link
  • 13.05.2015 / 06:41