JPA ManyToMany Join Table has all attributes as PK

前端 未结 2 517
梦毁少年i
梦毁少年i 2021-01-03 11:16

I\'m using Hibernate 3.3.1 and am following along in modelling this sample table structure, but I\'m having trouble creating a join table with extra attributes.

It\

2条回答
  •  时光取名叫无心
    2021-01-03 11:50

    You use class of your entity as an argument to IdClass. That is not correct. Class of Id should be used. Additionally separate fields for id in join entity are not needed.

    Go for something like code below. I cannot guarantee that it works in such a old version of Hibernate, but works for sure in never ones. Worth of trying anyway. It would not hurt to update to at least 3.5.X version (or rather even fresher one) if you want to use JPA 2.0 features. Constructors/equals etc. are stripped away to save space.

    @Entity
    @Table(name = "Orders")
    public class Order {
        @Id Long id;
        @OneToMany(mappedBy="order")
        private List orderItems;
    }
    
    @Entity
    @Table(name="PRODUCTS")
    public class Product {
        @Id Long id;
        @OneToMany(mappedBy="product")
        private List orderItems;
    }
    
    @Entity
    @IdClass(OrderDetailId.class)
    @Table(name = "ORDER_DETAIL")
    public class OrderDetail implements Serializable {
        @Id @ManyToOne @JoinColumn(name = "ORDER_ID")
        private Order order;
    
        @Id @ManyToOne @JoinColumn(name = "PRODUCT_ID")
        private Product product;
    
        @Column(name = "PRICE") private double price;
        //Maybe you also want to use @TemporalType here
        @Column(name = "LAST_UPDATED_TIME") private Date lastUpdatedTime;
    }
    
    public class OrderDetailId implements Serializable {
        private Long order;
        private Long product;
    }
    

    UPDATE 15/08/2017 In JPA 2.1 and above you don't need to add a class for the composite Id and you can do it like this:

    @Entity
    @Table(name = "ORDER_DETAIL")
    public class OrderDetail implements Serializable {
        @Id @ManyToOne @JoinColumn(name = "ORDER_ID")
        private Order order;
    
        @Id @ManyToOne @JoinColumn(name = "PRODUCT_ID")
        private Product product;
    
        @Column(name = "PRICE") private double price;
        //Maybe you also want to use @TemporalType here
        @Column(name = "LAST_UPDATED_TIME") private Date lastUpdatedTime;
    }
    

提交回复
热议问题