Search code examples
hibernateentity-relationship

How to map entity property with custom query and Hibernate


I have EntityA and EntityB with a OneToMany relation from EntityA -> EntityB. I would like to include EntityB as property into EntityA.

I only want to get the last one inserted of the many entities. Is there a way I can make a custom query to get the entity I want?

I tried to use @Formula annotation from that post, I get ERROR: subquery must return only one column And, if my query is select ct from ... I get 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;
}

The other workaround was to fetch and set that property in a method, but my goal is to find a solution within the entity class. Does someone have an idea? Thanks


Solution

  • The error message gives you the explanation. A formula must only return one column.

    You must change b.* to b.id.