How to implement a "one to zero" mapping?

Asked

Viewed 106 times

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... */
}
  • 3

    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.

  • @Caffe magically worked today when I went to test the same code, including using the same Insert.

1 answer

1


Try adding the annotation @NotFound with the attribute (action=NotFoundAction.IGNORE), 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:

  1. https://stackoverflow.com/questions/841354/
  2. https://stackoverflow.com/questions/7146064/
  3. http://www.concretepage.com/hibernate/example-notfound-hibernate
  • 1

    If it doesn’t work, let me know.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.