Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Multiple many-to-many relations between two entities?

I have two entity classes 'User' and 'Document'. Each user has an inbox and an outbox which are in fact two List and each Document may reside in multiple inbox's and outbox's of users. Here are my classes:

@Entity
public class User {

    @Id
    private Long id;

    @ManyToMany(mappedBy = "userinbox", cascade=CascadeType.ALL)
    private List<Document> inbox = new ArrayList<Document>();
    @ManyToMany(mappedBy = "useroutbox", cascade=CascadeType.ALL)
    private List<Document> outbox = new ArrayList<Document>();

}

@Entity
public class Document {

    @Id
    private Long id;

    @ManyToMany(cascade=CascadeType.ALL)
    private List<User> userinbox  = new ArrayList<User>();
    @ManyToMany(cascade=CascadeType.ALL)
    private List<User> useroutbox  = new ArrayList<User>();

}

When I run the programm and try to assign a document to a user's inbox (and vice-versa), I get the following error:

Error Code: 1364

Call: INSERT INTO DOCUMENT_USER (userinbox_ID, inbox_ID) VALUES (?, ?)
    bind => [2 parameters bound]

Internal Exception: java.sql.SQLException: Field 'useroutbox_ID' doesn't have a default value

Query: DataModifyQuery(name="userinbox" sql="INSERT INTO DOCUMENT_USER (userinbox_ID, inbox_ID) VALUES (?, ?)")

The generated association table looks like this:

DOCUMENT_USER
useroutbox_ID | outbox_ID |userinbox_ID | inbox_ID

How would I assign default values for such a many-to-many relation? Would it be better to make two association tables -> one for inbox-relation, another for outbox-relation? How would I accomplish that ? Other solutions to this problem ?

Any help highly appreciated - many thanks in advance!

like image 607
salocinx Avatar asked Apr 06 '12 12:04

salocinx


1 Answers

I think that the better option is to have two separate tables, one per relation. Because you actually have two relations between two different entities, and not one relation with four different entities.

So, you should add a @JoinTable annotation to each of your attributes in the Document side since the User side those relations are mapped to a property. Something like the following:

@Entity
public class Document {

    @Id
    private Long id;

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "document_inbox", joinColumns = @JoinColumn(name = "userinbox_id"),
               inverseJoinColumns = @JoinColumn(name = "inbox_id"))
    private List<User> userinbox  = new ArrayList<User>();
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "document_outbox", joinColumns = @JoinColumn(name = "useroutbox_id"),
               inverseJoinColumns = @JoinColumn(name = "outbox_id"))
    private List<User> useroutbox  = new ArrayList<User>();

}

Leave the other entity as it is now. Hope this helps.

like image 143
Alonso Dominguez Avatar answered Oct 21 '22 11:10

Alonso Dominguez