Reputation: 44104
I have these entities:
@Entity
public class Room {
@ManyToOne(optional=true,fetch=FetchType.LAZY)
private Player player1;
...
}
@Entity
public class Player {
@Id
@Column(updatable=false)
private long id;
public long getId() {
return id;
}
...
}
Now, this statement inside Room
...
player1.getId();
...will cause that entire Player
entity to be fetched from the database. However, I just need its primary key, id
, which it should already have (otherwise how can it fetch the data?).
How can I access the lazy Player
proxy's id
without triggering database access?
Upvotes: 5
Views: 874
Reputation: 44104
I've found a simpler solution, which is to make getId()
final
. This will prevent Hibernate from overriding it with lazy fetching action in the proxy, so it will just return the already known ID, without causing any issues.
Upvotes: 0
Reputation: 20063
You could have a attribute of @Column private long playerId
on the Room entity. You could call this attribute to get the id without having to call the entire Player object in the transaction.
This would only work if the playerId was also stored in the Room entity table (or view etc), but I assume it must be as it's needed to be able to make the join in the first place.
edit : as @Adam Dyga mentioned below, these should be insertable and updatable both as false
@Entity
public class Room {
@ManyToOne(optional=true,fetch=FetchType.LAZY)
private Player player1;
@Column(name="id", insertable = false, updatable = false)
private long playerId
...
}
Upvotes: 1
Reputation: 15240
Hibernate should keep the object's ids linked also to the current Session
. And there is a getIdentifier() method on the Session
that should get the id. The documentation is not saying anything about it, but normally it shouldn't initialize the object.
Upvotes: 4