【发布时间】:2019-12-02 17:06:16
【问题描述】:
我对在 Spring Data JPA 中使用投影有点困惑。 我想通过在一个查询中仅请求(最好)需要的列来优化我的查询,并且我认为使用投影是一个好主意。但似乎带有嵌套投影的投影变得开放并请求所有列并且进一步嵌套是不可能的。
我尝试使用@Query(找不到如何映射嵌套列表)、@EntityGraph(找不到如何请求仅指定的列)和@SqlResultSetMapping(找不到如何使映射嵌套列表),但它对我不起作用。
除了接收List<Object[]> 和手动映射,有没有其他解决方案?
我有下一个实体类(为问题简化):
public class TestAttempt{
private Long id;
private User targetUser;
private Test test;
}
public class Test{
private Long id;
private String name;
private Set<Question> questions;
}
public class Question{
private Long id;
private String name;
private Test test;
}
我想写这样的东西(它可以只是 TestAttempt 和 null 在未使用的字段):
public interface TestAttemptList {
Long getId();
Test getTest();
interface Test {
String getName();
List<Question> getQuestions();
interface Question {
String getName();
}
}
}
public interface TestAttemptRepository extends JpaRepository<TestAttempt, Long> {
List<TestAttemptList> getAllByTargetUserId(Long targetUserId);
}
结果是这样的:
{
id: 1,
test: {
name: test1,
questions: [{
name: quest1
}, {
name: quest2
}]
}
}
【问题讨论】:
-
@ alanhay,我试图手动编写查询,但似乎春天无法用2个字段映射嵌套实体,我得到只有一个表达式可以在选择列表中指定一个表达式EXISTS 没有引入子查询,即使我去掉查询中的问题字段,getTest() 方法也会抛出 IllegalAccessException 作为框架将测试映射为字符串
标签: java spring spring-data-jpa spring-data