【发布时间】:2019-08-16 16:10:56
【问题描述】:
我有 EntityA 和 EntityB 与来自 EntityA -> EntityB 的 OneToMany 关系。我想将 EntityB 作为属性包含到 EntityA 中。
我只想插入许多实体中的最后一个。有没有办法可以进行自定义查询来获取我想要的实体?
我尝试使用post 中的@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;
}
另一种解决方法是在方法中获取和设置该属性,但我的目标是在实体类中找到解决方案。有人有想法吗?谢谢
【问题讨论】:
标签: hibernate entity-relationship