JPA查询选择新的

时间:2018-03-01 11:01:20

标签: java spring jpa spring-data

查询:

@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);

构造函数:

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;
}

我没有得到任何附件。但是当我执行这个时:

@Query("SELECT ia from Attachment ia where ia.someClass=?1")
List<Attachment> findAllBySomeClass(SomeClass someClass);
然后我得到了我想要的一切。但我不需要所有这些字段,但只有第一个查询中列出的字段。为什么它不起作用?

从调试开始:它甚至不会进入这个构造函数。

1 个答案:

答案 0 :(得分:1)

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

由于您想要将关系属性添加到新的元组对象中,您必须自己进行正确的连接并为连接对象提供这样的查询

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