Java – JPA: many to many relationship between two entities?
I have two entity classes' user 'and' document ' Each user has an inbox and an outbox, which are actually two lists. Each document may reside in users with multiple inboxes and outboxes This is my course:
@Entity public class User { @Id private Long id; @ManyToMany(mappedBy = "userin@R_192_2419@",cascade=CascadeType.ALL) private List<Document> in@R_192_2419@ = new ArrayList<Document>(); @ManyToMany(mappedBy = "userout@R_192_2419@",cascade=CascadeType.ALL) private List<Document> out@R_192_2419@ = new ArrayList<Document>(); } @Entity public class Document { @Id private Long id; @ManyToMany(cascade=CascadeType.ALL) private List<User> userin@R_192_2419@ = new ArrayList<User>(); @ManyToMany(cascade=CascadeType.ALL) private List<User> userout@R_192_2419@ = new ArrayList<User>(); }
When I run the program and try to assign documents to the user's inbox (and vice versa), I receive the following error: @ h_ 502_ 5@
Error Code: 1364 Call: INSERT INTO DOCUMENT_USER (userin@R_192_2419@_ID,in@R_192_2419@_ID) VALUES (?,?) bind => [2 parameters bound] Internal Exception: java.sql.sqlException: Field 'userout@R_192_2419@_ID' doesn't have a default value Query: DataModifyQuery(name="userin@R_192_2419@" sql="INSERT INTO DOCUMENT_USER (userin@R_192_2419@_ID,?)")
The generated association table is as follows: @ h_ 502_ 5@
DOCUMENT_USER userout@R_192_2419@_ID | out@R_192_2419@_ID |userin@R_192_2419@_ID | in@R_192_2419@_ID
How do I assign default values to this many to many relationship? Would it be better to make two associated tables? > One for the inbox relationship and the other for the inbox relationship? How can I do this? Other ways to solve this problem@ H_ 502_ 5@
Any help is highly appreciated – thank you very much in advance@ H_ 502_ 5@
Solution
I think it's better to have two separate tables, one for each relationship Because there are actually two relationships between two different entities, rather than one relationship with four different entities
Therefore, you should add @ jointable annotation for each attribute on the document side, because the user side maps these relationships to attributes Similar to the following: @ h_ 502_ 5@
@Entity public class Document { @Id private Long id; @ManyToMany(cascade=CascadeType.ALL) @JoinTable(name = "document_in@R_192_2419@",joinColumns = @JoinColumn(name = "userin@R_192_2419@_id"),inverseJoinColumns = @JoinColumn(name = "in@R_192_2419@_id")) private List<User> userin@R_192_2419@ = new ArrayList<User>(); @ManyToMany(cascade=CascadeType.ALL) @JoinTable(name = "document_out@R_192_2419@",joinColumns = @JoinColumn(name = "userout@R_192_2419@_id"),inverseJoinColumns = @JoinColumn(name = "out@R_192_2419@_id")) private List<User> userout@R_192_2419@ = new ArrayList<User>(); }
Keep the current another entity I hope this will help@ H_ 502_ 5@