How to create a composite primary key which contains a @ManyToOne attribute as an @EmbeddedId in JPA?

旧街凉风 提交于 2019-11-28 10:13:34

I don't know of a way to do this which doesn't involve duplicating any fields (sorry!). But it can be done in a straightforward and standard way that involves duplicating only the relationship fields. The key is the @MapsId annotation introduced in JPA 2.

The embeddable key class looks like this:

@Embeddable
public class OrderLineKey {
    private int orderId;
    private int lineNo;
}

And the embedding entity class looks like this:

@Entity
public class OrderLine{
    @EmbeddedId
    private OrderLineKey id;

    @ManyToOne
    @MapsId("orderId")
    private Order order;
}

The @MapsId annotation declares that the relationship field to which it is applied effectively re-maps a basic field from the embedded ID.

Here's the code for OrderId.

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