Jack
Jack

Reputation: 6600

How to have Zero To Many relationship in Hibernate

I have a class called Member that has a few @OneToMany relationships with other classes. I can insert only one Member with empty OneToMany relationships. Upon inserting the second Member I receive following exception.

ERROR: Duplicate entry '' for key 'UK_7pn834d04yft1rkvpqf0viuyc'

Code

@Entity
public class Member {
    @Id
    @Column(name = "username", nullable = false, unique = true)
    private String email;
    @OneToMany(mappedBy = "friend")
    private Set<Friendship> friends;
    ....

To insert Member, I am adding empty set of friends to it. I suspect this and suppose need to have ZeroToMany relationship but could not find its annotation in Hibernate documentation.

Update

Member member = new Member(email, new HashSet<Friendship>());

Constructor

public Member(String email, Set<Friendship> friends) {
        super();
        this.email = email;
        this.friends = friends;
    }

toString

 member:Member [[email protected] , friends=[]]

console

insert 
        into
            Member
            (username) 
        values
            (?)

Upvotes: 2

Views: 8008

Answers (1)

zoran jeremic
zoran jeremic

Reputation: 2138

There is no ZeroToMany relationship. That doesn't exist and doesn't have sense. You can't connect 0 entities with many entities. You should use @OneToMany relationship here, and you should initialize friends collection

private Set<Friendship> friends = new HashSet<Friendship>();

if you didn't do that in some constructor which is not shown here.

I would suggest to turn on show_sql hibernate property so you can have more details about the problem.

Upvotes: 4

Related Questions