英文:
How to get object from nested entities in Spring/JPA/Hibernate?
问题
我有以下实体类:
public class AnswerEntity {
@ManyToOne
private UserEntity user;
@ManyToOne
private AnswerDirectoryEntity answer;
@ManyToOne
private QuestionEntity question;
}
public class QuestionEntity {
@ManyToOne
private QuestionnaireEntity questionnaire;
}
public class QuestionnaireEntity {
private String code;
}
我需要根据 "user ID" 获取所有用户的答案,以及来自 "QuestionnaireEntity" 的相应 "code"。
我通过创建如下查询来实现:
List<AnswerEntity> answerList = answerRepository.findAllByUserId(userId);
然后我迭代列表中的每个对象,并使用 "equals" 方法将每个对象与我的问卷代码进行比较:
for (AnswerEntity answerEntity : answerList) {
if (answerEntity.getQuestion().getQuestionnaire().getCode().equals(questionnaireId)) {
///
}
}
但是这个解决方案很慢,因为它必须迭代数据库中的每个对象。有没有人可以告诉我如何在我的存储库中创建一个可以帮助我的查询?
英文:
I have this entities:
public class AnswerEntity {
@ManyToOne
private UserEntity user;
@ManyToOne
private AnswerDirectoryEntity answer;
@ManyToOne
private QuestionEntity question;
}
public class QuestionEntity {
@ManyToOne
private QuestionnaireEntity questionnaire;
}
public class QuestionnaireEntity {
private String code;
}
I need to take all user answers by user ID
and corresponding code
from QuestionnaireEntity
.
I do it by create query like this:
List<AnswerEntity> answerList = answerRepository.findAllByUserId(userId);
and iterate over each object in my list and with using equals
I compare each object to my questionnaire code:
for(AnswerEntity answerEntity : answerList){
if(answerEntity.getQuestion().getQuestionnaire().getCode().equals(questionnaireId)){
///
}
but this solution is very slow because it must iterate each object from my database,
can anybody tell my how to create an query
in my repository which can help me?
答案1
得分: 1
你可以在仓库中这样使用 JPA 方法查询:
List<AnswerEntity> findByUserIdAndQuestionQuestionnaireCode(Integer userId, String code);
英文:
You can use JPA method query this way in repository
List<AnswerEntity> findByUserIdAndQuestionQuestionnaireCode(Integer userId, String code);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论