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