Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate getId is loading the object even though it is lazy

Tags:

hibernate

I remember there is an annotation either in JPA or hibernate to tell hibernate to use the getId/setId method instead of the property(we annotate our properties). Without this setting getId results in hitting the database and filling in all the fields of that object which is not what I want. Anyone know what that annotation is?

Example:

public void Project {
  @Id
  //Other annotation forcing hibernate to use property get/settter
  public Long id;
}

public Ticket {
  @ManyToOne(lazy=true)
  public Project project;
}

so, ticket.getProject.getId() results in hitting the database to get the project when the id is already in the hibernate project proxy object. The annotation will fix that I remember.

thanks, Dean

like image 983
Dean Hiller Avatar asked Feb 12 '12 16:02

Dean Hiller


1 Answers

You need to tell Hibernate to access the ID using property access rather than field access:

@Id
@Access(AccessType.PROPERTY)
private Long id;

You really should not make your fields public.

like image 173
JB Nizet Avatar answered Oct 04 '22 13:10

JB Nizet