读取实体 A 时从实体 B 读取值(非 PK 列上的左连接)- JPA 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在Entity中使用JoinColumn注解引用OtherEntity的一种方式,下面的代码是在Entity中。
A way to reference the OtherEntity in Entity using the JoinColumn annotation, the below code to be in Entity.
您可能想要使用 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.