简体   繁体   中英

JPA query Select new

Query:

@Query("SELECT new com.abc.cba.domain.Attachment(ia.createdBy, 
ia.fileName, ia.contentType, ia.someClass, ia.otherClass) from Attachment ia 
where ia.someClass=?1")
List<Attachment> findAllBySomeClass(SomeClass someClass);

And constructor:

public Attachment(User createdBy, String fileName, String contentType, SomeClass someClass, OtherClass otherClass) {
    this.createdBy = createdBy;
    this.fileName = fileName;
    this.contentType = contentType;
    this.someClass = someClass;
    this.otherClass = otherClass;
}

I don't get any Attachments. But when I execute this:

@Query("SELECT ia from Attachment ia where ia.someClass=?1")
List<Attachment> findAllBySomeClass(SomeClass someClass);

then i get everything i want. But i don't need all these fields, but only these listed in first query. Why it doesn't work?

From debugging: it doesn't even step into this constructor.

public Attachment(User createdBy, String fileName, String contentType, SomeClass someClass, OtherClass otherClass) 
//User, SomeClass, OtherClass wont work here like that

As you want to pick relational properties into new tuple object, you have to make proper joins yourself and provide joined objects with query like this

SELECT new com.abc.cba.domain.Attachment(user, ia.fileName, ia.contentType (....)) FROM Attachent ia JOIN ia.createdBy user JOIN ......" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM