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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With