7

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

Dean Hiller
  • 19,235
  • 25
  • 129
  • 212

1 Answers1

12

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Link here with some more detail; http://256.com/gray/docs/misc/hibernate_lazy_field_access_annotations.shtml – Joachim Isaksson Feb 12 '12 at 16:36
  • sorry, been using the playframework and you kind of get used to it after a while. I don't like public fields myself, but after using scala, I wish java had something like that to reduce the coding. – Dean Hiller Feb 12 '12 at 22:00
  • shoot, this generates a warning for every class it is on as JPA spec says that annotation has to go on the getId method but moving it there just results in an exception and won't work at all. How do do this properly these days??? (I used to use this on the field but it might have been the hibernate specific one)...thanks. – Dean Hiller Feb 12 '12 at 23:51
  • New URL for the lazy field access stuff: http://256stuff.com/gray/docs/misc/hibernate_lazy_field_access_annotations.shtml – Gray Jul 20 '16 at 19:11