如果连接关系在EmbeddedId上,如何使用Criteria API连接两个表

时间:2018-04-23 16:29:05

标签: java hibernate jpa relational-database criteria-api

我有以下课程:

@Entity 
public class EventOrderLine {

  @EmbeddedId   private EventOrderLineId id;

}

@Embeddable
public class EventOrderLineId implements Serializable {

  @ManyToOne
  @JoinColumn(name = "eventid")
  @JsonIgnore
  private Event event;

  @ManyToOne
  @JoinColumn(name = "orderlineid")
  @JsonIgnore
  private OrderLine orderLine;

}


@Entity   
public class OrderLine {

  @OneToMany
  @JoinColumn(name = "orderlineid")
  @JsonIgnore
  private List<EventOrderLine> eventOrderLines = new ArrayList<>()

}

基本上我试图通过Criteria API加入这两个表,但是因为这是我想做的事情所以有问题:

Root eventOrderLine = criteriaQuery.from(EventOrderLine.class);
Join orderLine = eventOrderLine.join("orderLine");

当然这给了我这个问题,因为映射不直接在实体本身上:

Unable to locate Attribute  with the the given name [orderLine] on this ManagedType [com.EventOrderLine]

我一直在尝试调整连接以深入了解embeddedId但不确定我是否需要更进一步并修改我的实体的映射方式。我觉得这可能是一件很简单的事情,但我很难找到这个具体的问题。

2 个答案:

答案 0 :(得分:1)

event字段是EventOrderLineId的成员,而不是EventOrderLine。在条件查询中,您首先需要导航到id。问题是Root.path("id")返回Path的实例,不允许进一步的连接。

诀窍是使用假冒的&#39;加入id字段,如下所示:eventOrderLine.join("id").join("event")

eventOrderLine.get("id").get("event")可能也会起作用,但它不允许您指定连接类型。

答案 1 :(得分:0)

首先尝试获取id实体的属性EventOrderLine,然后加入。所以,它会是 -

Root eventOrderLine = criteriaQuery.from(EventOrderLine.class);
Join orderLine = eventOrderLine.get("id").join("orderLine")
相关问题