I have a model with two many-to-many relationships. Play framework creates the relationship tabel for me, but none of the ids are nullable, resulting with me unable to get my code to work.
Play framework returns PersistenceException occured : insert into Costumer_Item (customersWhoIgnored_id, ignor开发者_开发问答edItems_id) values (?, ?)
19:20:54,530 ERROR ~ Field 'customersWhoBought_id' doesn't have a default value
19:20:54,531 ERROR ~ Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
The code is Item.java:
@Entity
public class Item extends Model {
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "ownedItems")
public List<Costumer> customersWhoBought;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "ignoredItems")
public List<Costumer> customersWhoIgnored;
}
Customer.java:
@Entity
public class Customer extends Model {
@Column(nullable = true)
@ManyToMany(cascade = CascadeType.ALL)
public List<Item> ownedItems;
@Column(nullable = true)
@ManyToMany(cascade = CascadeType.ALL)
public List<Item> ignoredItems;
}
How do I get many @ManyToMany relationships to work?
I think both relationships use the same join table with default name Costumer_Item
, which causes confusion. You need to specify different names manually:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "CostumerToOwnedItems")
public List<Item> ownedItems;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "CostumerToIgnoredItems")
public List<Item> ignoredItems;
I would strongly recommend not using the ManyToMany, and instead just use one-to-many and many-to-one relationships, with an explicit domain object for the middle. It's very easy to get confused with ManyToMany (as you are finding), and you very often wind up having to add additional data to the ManyToMany anyways.
Also, FWIW, this is a lot more of a JPA/Hibernate issue than a Play framework issue.
精彩评论