Record projection with another record projection

618 Views Asked by At

I get problem with nessted projection. (inside projection)

Root entity:

@Entity(name = "AAA")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class AAA{

    @Id
    private Long id;

    @OneToOne
    private BBB bbb;
}

where BBB looks like this:

@Entity(name = "BBB")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class BBB{

    @Id
    private Long id;

    @Column(name = "name")
    private String name;

Projections

public record AAAProjection(
       Long id, 
       BBBProjection bbb                            
) {
}

public record BBBProjection(
       Long id, 
       String name                            
) {
}

When I try to query with these projections, an exception is thrown: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class AAAProjection

Is there any way to use nested projection in projection in Spring Boot Data JPA?

1

There are 1 best solutions below

0
On

I solved this using traversing in projection, like this:

public record AAAProjection(
       Long id, 
       Long bbbId,
       String bbbName                                                                         
) {
}

To get a field from a nested entity just use its name in the projection, here is BBBProjection bbb so there is the pattern like: bbb<FieldName>