Helosze
Helosze

Reputation: 363

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.

Upvotes: 0

Views: 4871

Answers (1)

Antoniossss
Antoniossss

Reputation: 32507

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 ......" 

Upvotes: 2

Related Questions