读取实体 A 时从实体 B 读取值(非 PK 列上的左连接)- JPA 2.0

发布于 2024-12-29 08:24:43 字数 968 浏览 2 评论 0原文

所以我有:

@Entity
public class Entity {

  @EmbeddedId
  private MyId id;

  // not a part of Entity but a part of OtherEntity
  private String lookedUpValue;

}

public class MyId {
   private String firstField;
   private String secondField;
}

表看起来像:

ENTITY
  FIRSTFIELD (PK)
  SECONDFIELD (PK)
  // etc.

public class OtherEntity {
  private String firstField;
  private String value;
}

表看起来像:

OTHERENTITY
  VALUE (PK)
  FIRSTFIELD 
  //etc.
}

当我读取实体时,我希望有一个 LEFT JOIN 来填充其 LookUpValue 字段,其中 Entity.id.firstField = OtherEntity.firstField 即在 SQL 中将是:

Select ENTITY.FIRSTFIELD, ENTITY.SECONDFIELD, OTHERENTITY.VALUE 
from ENTITY
left join OTHERENTITY
ON ENTITY.FIRSTFIELD = OTHERENTITY.FIRSTFIELD

因此实体实例将填充所有这些字段。

这可能吗,或者您推荐另一种方法吗?将 OtherEntity 作为每个实体上的字段读取也可以工作 - 但因为 MyId 没有映射到 OtherEntity,我不知道如何实现这一点。多谢。

so I have:

@Entity
public class Entity {

  @EmbeddedId
  private MyId id;

  // not a part of Entity but a part of OtherEntity
  private String lookedUpValue;

}

public class MyId {
   private String firstField;
   private String secondField;
}

Table looks like:

ENTITY
  FIRSTFIELD (PK)
  SECONDFIELD (PK)
  // etc.

public class OtherEntity {
  private String firstField;
  private String value;
}

Table looks like:

OTHERENTITY
  VALUE (PK)
  FIRSTFIELD 
  //etc.
}

When I read Entity I want there to be a LEFT JOIN to populate its lookedUpValue field where Entity.id.firstField = OtherEntity.firstField i.e. in SQL it would be:

Select ENTITY.FIRSTFIELD, ENTITY.SECONDFIELD, OTHERENTITY.VALUE 
from ENTITY
left join OTHERENTITY
ON ENTITY.FIRSTFIELD = OTHERENTITY.FIRSTFIELD

So Entity instances would get populated with all these fields.

Is this possible, or do you recommend another approach? Reading OtherEntity as a field on each Entity could work too - but because MyId does not map to OtherEntity I do not see how to achive that. Thanks a lot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只是一片海 2025-01-05 08:24:43

在Entity中使用JoinColumn注解引用OtherEntity的一种方式,下面的代码是在Entity中。

@OneToOne(optional="true")
@JoinColumn(name="FIRSTFIELD",referencedColumnName="FIRSTFIELD")
OtherEntity otherEntity;

A way to reference the OtherEntity in Entity using the JoinColumn annotation, the below code to be in Entity.

@OneToOne(optional="true")
@JoinColumn(name="FIRSTFIELD",referencedColumnName="FIRSTFIELD")
OtherEntity otherEntity;
苍风燃霜 2025-01-05 08:24:43

您可能想要使用 JPQL 构造函数表达式 此处。

基本上,您创建一个包含所需所有字段的 DTO,并在查询中使用它的构造函数(带有 NEW)。

You might want to use JPQL Constructor Expressions here.

Basically, you create a DTO with all the fields you need and use it's constructor (with NEW) in the query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文