Hibernate select id of join column without join

A.Shaheri :

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.

Obi Wan - PallavJha :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77628&siteId=1