QueryDSL projections with @ManyToOne relation

人盡茶涼 提交于 2019-12-21 18:27:09

问题


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



来源:https://stackoverflow.com/questions/27705687/querydsl-projections-with-manytoone-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!