Mapping Extra Attribute in a Join Table JPA 2

时间秒杀一切 提交于 2019-12-03 14:02:21

问题


I am trying to model this relationship following this link http://www.javaworld.com/javaworld/jw-01-2008/images/datamodel.gif

Its the usual Many to Many relationship between Order and Products but I dont know how to add the extra columns in the Join table.

@Entity
@Table(name = "Orders")
public class Order {
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "ORDER_LINES", joinColumns = { @JoinColumn(name = "ORDER_ID") }, inverseJoinColumns = { @JoinColumn(name = "PROD_ID") })
    private Set<Product> products;
}

@Entity
@Table(name="PRODUCTS")
public class Product {
    @ManyToMany(mappedBy="products")
    private Set<Order> orders;
}

How to add Join Table extra attribute in JPA 2.0?

Thanks


回答1:


There is no concept of having additional persistent attribute in relation in JPA (2.0). That's why relation with property is actually intermediate entity.

From both Order and Product entities, you need one-to-many relationship to new entity. Because of bidirectional relationship, new entity will have many-to-one relationships to Order and Product.

You need to go for something like this (shows only relationships, id's and other mappings stripped away):

@Entity
@Table(name="order_item")
public class OrderItem {
    @ManyToOne
    private Order order;
    @ManyToOne
    private Product product;
}

@Entity
public class Order {
    @OneToMany (mappedBy = "order")
    private Set<OrderItem> orderItems;
}

@Entity
public class Product {
    @OneToMany(mappedBy = "product")
    private Set<OrderItem> orderItems;
}


来源:https://stackoverflow.com/questions/9816932/mapping-extra-attribute-in-a-join-table-jpa-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!