简体   繁体   中英

How to get object from nested entities in Spring/JPA/Hibernate?

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?

You can use JPA method query this way in repository

List<AnswerEntity> findByUserIdAndQuestionQuestionnaireCode(Integer userId, String code);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM