For example, there is an entity "User" with @ManyToOne(fetch=Lazy)
field "Team". I have used entityManager.find(User.class, userId)
get a user. At this point, if I call user.getTeam()
a query will be send to database to get team object. Is there a way to get the team id without extra query?
Asked
Active
Viewed 2,448 times
2

Jiang Zhu
- 97
- 1
- 8
-
Related question is more answers https://stackoverflow.com/questions/2593722/hibernate-one-to-one-getid-without-fetching-entire-object – Sergey Ponomarev Jul 09 '20 at 11:18
2 Answers
5
For these purposes I do map the column twice. Once as many-to-one with insert="true"
and update="true"
.
then I append an TeamId property and mapp it as int insert="false"
and update="false"
. Instead of column
mapping I use formula
.
TeamId is then available after the first select.

Radim Köhler
- 122,561
- 47
- 239
- 335
-
Thanks for the suggestion, we are currently using JPA annotations and trying to avoid using Hibernate specific feature. Do you know if I can use `@Column(updatable=false, insertable=false)` for this? – Jiang Zhu Nov 12 '12 at 11:51
-
I would say this is it. check the Formula mapping as well, because we will use one column twice – Radim Köhler Nov 12 '12 at 11:55
1
If you do not want to use Hibernate, add a @PostLoad method on you User entity, which will set your teamId
- Add a @Transient teamId property
- Add a @PostLoad method :
Add a @PostLoad method
@PostLoad
public void updateTeamIdInfos() {
if (getTeam() != null) {
setTeamId(getTeam().getId());
}
}

willome
- 3,062
- 19
- 32
-
2thanks for the reply, but this won't work for my very specific case. I was trying to avoid calling getTeam() function which will trigger lazy load – Jiang Zhu Nov 13 '12 at 06:54