我想模拟实体'order'和'items'
之间的样本m:n关系相应的映射部分是:
Order.java:
...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ORDER_ID")
private Long orderId;
@Column(name="ORDER_DESCRIPTION")
private String description;
@JoinTable(name ="ORDER_ITEMS",
joinColumns=@JoinColumn(name="ORDER_ID", referencedColumnName="ORDER_ID"),
inverseJoinColumns=@JoinColumn(name="ITEM_ID", referencedColumnName="ITEM_ID"))
private Set<Item> items;
...
Item.java:
...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ITEM_ID")
private Long itemId;
@Column(name = "ITEM_DESCRIPTION")
private String description;
@Column(name = "ITEM_PRICE")
private Long price;
@ManyToMany(mappedBy="items")
private Set<Order> orders;
...
您知道为什么我无法反向获取特定项目引用的订单吗? @ManyToMany(mappedBy =“items”)部分为我提供了“此关系的无效映射类型”。我以为我可以创建任意商品和订单,将商品添加到订单中,然后获得有关商品的所有订单。
在我的例子中,item.getOrders()给了我一个NullPointerException。
非常感谢!
答案 0 :(得分:2)
只是因为您忘记在项目上添加ManyToMany注释:
@ManyToMany
@JoinTable(name ="ORDER_ITEMS",
joinColumns=@JoinColumn(name="ORDER_ID", referencedColumnName="ORDER_ID"),
inverseJoinColumns=@JoinColumn(name="ITEM_ID", referencedColumnName="ITEM_ID"))
private Set<Item> items;