如何使用自定义查询和 Hibernate 映射实体 属性

How to map entity property with custom query and Hibernate

我有 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;
}

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

错误信息给你解释。一个公式只能return一个列。

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