How to implement a complex many to many relationship in JPA?

前端 未结 3 699
独厮守ぢ
独厮守ぢ 2020-12-30 17:00

Here the db schema

CREATE TABLE Products
(
    id          INT NOT NULL AUTO_INCREMENT,
    category_id  INT NOT NULL,
    description VARCHAR(100),
    pric         


        
3条回答
  •  没有蜡笔的小新
    2020-12-30 17:23

    From the EmbeddedId javadoc:

    Relationship mappings defined within an embedded id class are not supported.

    So you cannot do it this way. I don't think JPA 1 specifies a standard way to implement this (in JPA 2 there is @MapsId but I never tried), but this is what I usually do and most implementations (I think at least Hibernate, EclipseLink and OpenJPA) support it:

    Declare your primary key class using primitive types:

    @Embeddable
    public class OrderDetailPK implements Serializable
    {
        private int product;
        private int order;
    
        public OrderDetailPK() {}
    
        ...
    }
    

    Annotate your entity with @IdClass and declare the fields using the same name but the desired types:

    @Entity
    @IdClass(OrderDetailPK.class)
    public class OrderDetail {
        @Id
        @ManyToOne(cascade=CascadeType.ALL)
        @JoinColumn(name="product_id", insertable=false, updatable=false)
        private Product product;
    
        @Id
        @ManyToOne(cascade=CascadeType.ALL)
        @JoinColumn(name="order_id", insertable=false, updatable=false)
        private Order order;
    
        ...
    }
    

    (I have always kept the @Id on the fields in the entity but I didn't recheck if they are mandatory)

提交回复
热议问题