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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With