【问题标题】:How to join two tables using Criteria API if join relationship is on EmbeddedId如果连接关系在 EmbeddedId 上,如何使用 Criteria API 连接两个表
【发布时间】:2018-04-23 16:29:04
【问题描述】:

我有以下课程:

@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,但不确定是否需要更进一步并修改我的实体的映射方式。我觉得这可能是我想念的一些简单的东西,但很难找到这个特定的问题。

【问题讨论】:

  • 你试过eventOrderLine.join("id").join("event")吗?
  • 我相信这是正确的解决方案!我知道这很简单。如果您将此评论作为答案,我会接受。

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


【解决方案1】:

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

诀窍是使用带有 id 字段的“假”连接,如下所示:eventOrderLine.join("id").join("event")

eventOrderLine.get("id").get("event") 可能也可以正常工作,但它不允许您指定连接类型。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • Get 返回一个没有连接方法的路径
    猜你喜欢
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2015-03-23
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2012-08-20
    相关资源
    最近更新 更多