具有@ManyToOne关系的QueryDSL投影 [英] QueryDSL projections with @ManyToOne relation
问题描述
我将OpenJPA与QueryDSL一起使用,我尝试避免通过使用QueryDSL的bean投影功能来操纵Tuple对象.例如,我有这两个实体,具有@ManyToOne关系.
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;
}
当我执行此查询时:
List<Folder> listFolders = query.from(folder)
.list(Projections.bean(Folder.class, folder.name, folder.file.fileName));
我有一个错误,说Folder对象不包含fileName属性.
I have an error saying that the Folder object doesn't contain the fileName property.
我了解QueryDSL在做什么,因为它是一个简单的平面"投影,但是我想知道是否可以用查询找到的值填充我的folder.file对象的fileName属性.
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:我知道我可以为Folder类定义一个构造函数并使用此方法:
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));
但是我想尽可能避免这种情况,因为它迫使我为投影中想要的N个字段定义N个构造子.
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.
推荐答案
在这种情况下,您可以使用嵌套投影
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")));
这里是构造函数和bean投影的更明确的替代方法,在这种情况下也应如此
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;
}
};
相关 http://www.querydsl .com/static/querydsl/3.6.0/apidocs/com/mysema/query/types/MappingProjection.html
这篇关于具有@ManyToOne关系的QueryDSL投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!