2

I have a project with Spring Boot, and I cannot make lazy loading work. I have 2 entities: Question and Answer. A question can have many answers. What I want is, when I try to get an answer, to get only the answer without the question. And also, if I want both, to have this possibility.

What I did, is I added in application.yml: spring.jpa.open-in-view: true. The Answer entity is like:

@Entity
@Table(name = "mst_ans_answer", schema = "lquest_sc")
public class Answer implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "lquest_sc.mst_ans_answer_ans_lqs_id_seq")
    @SequenceGenerator( name = "lquest_sc.mst_ans_answer_ans_lqs_id_seq", sequenceName = "lquest_sc.mst_ans_answer_ans_lqs_id_seq")
    @Column(name = "ans_lqs_id")
    private int id;

    @Column(name = "qst_lqs_id")
    private int questionId;

    @Column(name = "ans_text")
    private String text;


    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "qst_lqs_id", insertable=false, updatable=false)
    @JsonIgnore
    private Question question;

    //getters and setters
}

The Question entity is:

@Entity
@Table(name = "mst_qst_question", schema = "lquest_sc")
public class Question implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "lquest_sc.mst_qst_question_qst_lqs_id_seq")
@SequenceGenerator(name = "lquest_sc.mst_qst_question_qst_lqs_id_seq", sequenceName = "lquest_sc.mst_qst_question_qst_lqs_id_seq")
@Column(name = "qst_lqs_id")
private int id;

@Column(name = "qst_title")
private String title;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "question")
@OrderBy("order asc")
private Set<Answer> answers = new HashSet<Answer>();


//getters and setters here

The call in the controller is:

@RequestMapping(value = "/questionId/{id}", method = RequestMethod.GET)
public List<Answer> listAll( @PathVariable("id") int id ){
    List<Answer> answers = answerRepository.findByEnabledAndQuestionIdOrderByOrderAsc(1,id);
    return answers;
}

and the repository is

public interface AnswerRepository extends JpaRepository<Answer, Long> {
    List<Answer> findByEnabledAndQuestionIdOrderByOrderAsc(int enabled,int questionId);
}

The problem is that in the controller, when I try to evaluate answers.get(0).getQuestion(), I receive the entity of Question, with the properties filled with null values and the error Method threw 'org.hibernate.LazyInitializationException' exception. Cannot evaluate Question_$$_jvst5b6_1.toString(). What am I doing wrong?

6
  • Hi Bodgan like Many to one mapping in Answer entity ,have you written Question entity with OnetoMany mapping?
    – Pradeep
    Jun 13, 2017 at 12:34
  • Can you please update your Question Entity also
    – Pradeep
    Jun 13, 2017 at 12:34
  • i did. and i readed that i had to add @transactional ? is this needed? and where to add, inside controller, or inside AnswerRepository?
    – bogdan
    Jun 13, 2017 at 13:57
  • in repository you need to add the @transactional i.e inside the impl class of repository where you have written your business logic.
    – Pradeep
    Jun 13, 2017 at 14:09
  • is the same. i have added at the end of the post the error that appear! (it was and at the beginning of posting but i forgot to post it)
    – bogdan
    Jun 13, 2017 at 14:44

1 Answer 1

1

I don't know why spring.jpa.open-in-view = true is not working in your case. Maybe the OpenEntityManagerInViewInterceptordoes not get triggered or the thread has been left, when you are evaluating the Question. Or you have an older version which just does not support it.

Lazy loading works only inside of a transaction. A solution could be - as @Pradeep already gave you the hint - to use @Tranactional inside a business logic class.

Even if you put the @Transactional inside your repository it will not work, because you have to put the annotation on top of the method where you are trying to evaluate answers.get(0).getQuestion().

Furthermore I advise you not to call your repository from the controller directly, but to use a service layer, where you put your business logic.


Example implementation

This is only a example implementation to show you how to structure your application and what the important keywords are. Also note, that you can either use @Inject or @Autowired. When you have implemented your logic, just inject the service into your controller and use it there.

AnswerService.java

public interface AnswerService {
   List<Answer> findByEnabledAndQuestionIdOrderByOrderAsc(int enabled, Long id);
}

AnswerServiceImpl.java

@Service
public class AnswerServiceImpl implements AnswerService {

    private AnswerRepository answerRepository;

    @Inject
    public AnswerServiceImpl(AnswerRepository answerRepository) {
        this.answerRepository = answerRepository;
    }

    @Transactional
    @Override
    public List<Answer> findByEnabledAndQuestionIdOrderByOrderAsc(int enabled, Long id) {
        List<Answer> answerList = findByEnabledAndQuestionIdOrderByOrderAsc(int enabled,int questionId);

        // do your lazy loading here
        // because you are still in the same transactional context

        // return the list
        return answerList;
    }
}
1
  • 10x for your comment. my mistake, was that, i was looking with the inspector from intellijidea, and there, if i evaluate the local variable questions, that holds the answers list, there, the question was null. but after that, if i try to do an inspection of answers.get(0).getQuestion, in debugger a new call to database apear and gets the question details. so, the lazy operation is done ok. now, the problem is, if i try to get the list of questions, automatically gets and the list of answers and this is not ok, because, it should load only if i do this: questions.get(0).getAnswers()
    – bogdan
    Jun 16, 2017 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.