【问题标题】:Spring Data JPA mapping nested entitiesSpring Data JPA 映射嵌套实体
【发布时间】: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;
}

我想写这样的东西(它可以只是 TestAttemptnull 在未使用的字段):

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

【问题讨论】:

  • 这能回答你的问题吗? JPA Projection with custom collection property
  • @ alanhay,我试图手动编写查询,但似乎春天无法用2个字段映射嵌套实体,我得到只有一个表达式可以在选择列表中指定一个表达式EXISTS 没有引入子查询,即使我去掉查询中的问题字段,getTest() 方法也会抛出 IllegalAccessException 作为框架将测试映射为字符串

标签: java spring spring-data-jpa spring-data


【解决方案1】:

我已经做过这样的事情...您将拥有您的存储库接口,它将扩展 CrudRepository 等。人。使用完整的对象(TestAttempt 等)您单独定义您的投影。投影接口可以包含其他投影接口(TestAttemptSummary 可以包含 TestSummary)当在给定存储库中使用投影接口时,定义的方法将应用于配置存储库的对象类型。像这样。

public interface TestAttemptSummary {
    Long getId();
    TestSummary getTest();
}

public interface TestSummary {
    String getName();
    List<QuestionSummary> getQuestions();
}

public interface QuestionSummary {
    String getName();
}

public interface TestAttemptRepository extends CrudRepository<TestAttempt, Long> {
    TestAttemptSummary getTestAttemptSummary();
}

【讨论】:

  • 我试图这样做。但是问题不通过查询获取(生成的查询如下所示:select ... from test_attempt ta inner join test t on ta.test_id = t.id),所以当我尝试时得到 LazyInitializationException从测试中获取问题()。
猜你喜欢
  • 2021-05-21
  • 2016-06-17
  • 2020-02-21
  • 2023-03-18
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
相关资源
最近更新 更多