我对在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;
}
我想写这样的代码(可以只使用null
填充未使用的字段):TestAttempt
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
}]
}
}