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

huangapple go评论72阅读模式
英文:

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&lt;AnswerEntity&gt; 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&lt;AnswerEntity&gt; findByUserIdAndQuestionQuestionnaireCode(Integer userId, String code);

huangapple
  • 本文由 发表于 2020年5月30日 23:25:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/62104623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定