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!
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
@JoinTableannotation to each of your attributes in theDocumentside since theUserside those relations are mapped to a property. Something like the following:Leave the other entity as it is now. Hope this helps.