Search code examples
springhibernatejpalazy-loadingjavassist

When are Entities-Classes enhanced and what for? jpa, spring, hibernate, javassist


I am using spring 3.0.6, jpa 2.0, hibernate 3.6.8. My question is, in which situations is javassist used to create "proxy" for a EntityClass? And what is reason of this proxy? I have the following Entity:

@Entity
public MyEntity{
..

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "adresseID")
  private Adresse adresse;

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "myEntity")
  private List<Parameter> parameters;

..
}

When I load a MyEntity from db, the class of entity is something like MyEntity__$$_javassist. Why is it done? What for? I think that just regular class MyEntity can be used here .

To implement lazy loading, we can:

  • for @OneToMany - PersistenceBag can be used here
  • for @ManyToOne - here should be used "enchancedClass" like Adress_$$_javassist

So what is reason for enchancing MyEntity? Where I can read something more about it? Which book/article/blog can you recommend me?


Solution

  • The primary reason why entity classes are enhanced is that JPA (or Hibernate) need to track entity objects state.

    In particular JPA must be aware if given entity field is "dirty" - it was modified by user, but this change is not yet reflected in database, so JPA must synchronize it with database when transaction is commited.

    The other case is "loaded" state of the entity field. Any field can be assigned to be lazy loaded. When such field is about to be used, JPA must be aware that database query has to be performed to initialize value of that field.

    Hibernate's default is to use runtime enhacement - the proxy is just a subclass of the entity with extra stuff added.

    Some general ideas are outlined here.