QueryDSL projections with @ManyToOne relation

2020-07-17 05:36发布

问题:

I'm using OpenJPA with QueryDSL, I try to avoid manipulating Tuple objects by using the bean projections features of QueryDSL. I have for example these two Entity, with a @ManyToOne relation.

@Entity
public class Folder {
    private Long id;
    private String name;
    private String path;
    @ManyToOne
    @JoinColumn(name = "FK_FILE_ID")
    private File file;
}

@Entity
public class File {
    private Long id;
    private String fileName;
}

When I'm executing this query :

List<Folder> listFolders = query.from(folder)
.list(Projections.bean(Folder.class, folder.name, folder.file.fileName));

I have an error saying that the Folder object doesn't contain the fileName property.

I understand what QueryDSL is doing, since it is a simple "flat" projection, but I would like to know if it is possible to fill the fileName attribute of my folder.file object with the found value by the query.

NB : I know that I can define a constructor for my Folder class and use this method :

query.list(ConstructorExpression.create(Folder.class, folder.name,
folder.file.fileName));

But I want to avoid this if possible, because it forces me to define N-constructors, for the N-combinations of fields I want in my projections.

回答1:

You can use nested projections for this case

List<Folder> listFolders = query.from(folder)
    .list(Projections.bean(Folder.class, folder.name, 
          Projections.bean(File.class, folder.file.fileName).as("file")));

Here is a more explicit alternative to constructor and bean projection that should also work for this case

MappingProjection<Folder> mapping = new MappingProjection<Folder>(Folder.class, folder.name, folder.file.fileName) {
 @Override
 protected Folder map(Tuple row) {
     Folder f = new Folder();         
     f.setName(row.get(folder.name));
     File file = new File();
     file.setFileName(row.get(folder.file.fileName));
     f.setFile(file);
     return f;
 }            

};

Related http://www.querydsl.com/static/querydsl/3.6.0/apidocs/com/mysema/query/types/MappingProjection.html