【问题标题】:How to map entity property with custom query and Hibernate如何使用自定义查询和 Hibernate 映射实体属性
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 是的,它正在工作!我认为我不仅需要参考 id 来获得完整的实体。谢谢!
    猜你喜欢
    • 2011-06-22
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2017-11-02
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多