hibernate - 如何使用自定义查询和 Hibernate 映射实体属性
问题描述
我有 EntityA 和 EntityB 与来自 EntityA -> EntityB 的 OneToMany 关系。我想将 EntityB 作为属性包含在 EntityA 中。
我只想插入许多实体中的最后一个。有没有办法可以进行自定义查询来获取我想要的实体?
我尝试使用该帖子中的@Formula 注释,我得到ERROR: subquery must return only one column
而且,如果我的查询是select ct from ...
我得到ERROR: column entityA.ct does not exist
@Data
@Entity
public class EntityA {
private static final String QUERY =
"(SELECT b.* FROM entity_b_table b
WHERE b.entity_a_id = id
ORDER BY b.created_at DESC
LIMIT 1)"
@Id
@GeneratedValue
private UUID id;
private String firstName;
@Column(updatable = false)
private LocalDateTime createdAt;
// What is the best way to achive this?
@ManyToOne
@JoinColumnsOrFormulas({
@JoinColumnOrFormula(formula = @JoinFormula(value = QUERY, referencedColumnName = "id")),
})
private EntityB entityB;
}
@Data
@Entity
public class EntityB {
@Id
@GeneratedValue
private UUID id;
private String lastName;
@Column(updatable = false)
private LocalDateTime createdAt;
private UUID entityAId;
}
另一种解决方法是在方法中获取和设置该属性,但我的目标是在实体类中找到解决方案。有人有想法吗?谢谢
解决方案
错误消息为您提供了解释。一个公式只能返回一列。
您必须更改b.*
为b.id
.
推荐阅读
- python-3.x - 检查列表中的第 1、2 和 3 个元素是否为整数 Python 3
- php - Woocommerce webhook 响应 200 消息 Rest API 不可用
- python - 你如何在 tkinter 中制作字体对话框?
- java - Flink OutputTag 可以复用吗?
- python-3.x - 对于这种特殊情况,如何使用地理编码获得公司的正确位置?(Python、谷歌 API)
- python - 如何添加多个熊猫数据框的每个条目。Python
- javascript - 带有 Stripe CardElement 的表单的返回值未定义 React Axios
- powerbi - 百分比的 DAX 阈值度量
- python - VisualStudioCodeCredential.get_token 失败
- python-3.x - 将 functools.partial 和 map 与内置的 getattr 一起使用?