Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从Spring/JPA/Hibernate中的嵌套实体获取对象?_Java_Spring_Hibernate_Spring Boot_Jpa - Fatal编程技术网

Java 如何从Spring/JPA/Hibernate中的嵌套实体获取对象?

Java 如何从Spring/JPA/Hibernate中的嵌套实体获取对象?,java,spring,hibernate,spring-boot,jpa,Java,Spring,Hibernate,Spring Boot,Jpa,我有以下几点: public class AnswerEntity { @ManyToOne private UserEntity user; @ManyToOne private AnswerDirectoryEntity answer; @ManyToOne private QuestionEntity question; } 我需要通过用户ID和相应的code从questionnairentity获取所有用户答案 我通过如下方式创建查询:

我有以下几点:

public class AnswerEntity {
    @ManyToOne
    private UserEntity user;
    @ManyToOne
    private AnswerDirectoryEntity answer;
    @ManyToOne
    private QuestionEntity question;
}
我需要通过
用户ID
和相应的
code
questionnairentity
获取所有用户答案

我通过如下方式创建查询:

List<AnswerEntity> answerList = answerRepository.findAllByUserId(userId);
但是这个解决方案非常慢,因为它必须迭代数据库中的每个对象


谁能告诉我如何在我的存储库中创建一个
查询
,这对我有帮助吗?

您可以在存储库中使用JPA方法以这种方式进行查询

List<AnswerEntity> findByUserIdAndQuestionQuestionnaireCode(Integer userId, String code);
List findbyuseriedandQuestionQuestionNaireCode(整数用户ID,字符串代码);

实体之间是否定义了任何关系?@Eklavya是的,我编辑了主要帖子您只想查看
questionnaireId
并仅获取那些
answerEntity
?或者全部提取,然后执行一些操作定义一个查询,提取用户的问题和问卷。在JPQL中,这类似于
从应答实体a join fetch a.question q join fetch q.questionly中选择一个。
或者在where子句中编写一个包含“if”语句的查询。像
从回答实体a中选择一个join a.question q join q.question qu where qu.code=yourCode
(还没有尝试这些语句,可能需要一些微调)@TomStroemer我不想使用这个JPQL,但我想在存储库中创建一个查询
List<AnswerEntity> answerList = answerRepository.findAllByUserId(userId);
for(AnswerEntity answerEntity : answerList){
            if(answerEntity.getQuestion().getQuestionnaire().getCode().equals(questionnaireId)){
     ///
}
List<AnswerEntity> findByUserIdAndQuestionQuestionnaireCode(Integer userId, String code);