首页 > 解决方案 > 如何使用自定义查询和 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;
}

另一种解决方法是在方法中获取和设置该属性,但我的目标是在实体类中找到解决方案。有人有想法吗?谢谢

标签: hibernateentity-relationship

解决方案


错误消息为您提供了解释。一个公式只能返回列。

您必须更改b.*b.id.


推荐阅读