Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate select id of join column without join

The problem is I need to select an object from database which has a join column inside, and I need the Id of that foreign object. But hibernate joins those two tables or if in lazy mode , It queries again on my database. How do I access that Id with no other join or query than the primary select query.

Note that I am using Hibernate version +5 and I want an approach via JPA CriteriaBuilder.

Thank you in advance.

like image 624
A.Shaheri Avatar asked Sep 24 '18 09:09

A.Shaheri


1 Answers

You can map the foreign key to the entity twice in this case, one for actual ORM and another for getting the FK without actually firing a new query.

public class Answer {
   @JoinColumn(name = "question_id")
   @ManyToOne(targetEntity = Question.class, fetch = FetchType.LAZY)
   private Question question;

   @Column(name = "question_id", insertable = false, updatable = false)
   private Long questionId;
}

Here question_id is present in the answer table.

This way that foreign key will be already available in the result of the first query(in the questionId field) and the new query won't be fired for getting the FK value.

like image 91
Pallav Jha Avatar answered Oct 25 '22 20:10

Pallav Jha