Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 246
dpolaczanski Avatar asked May 16 '12 19:05

dpolaczanski


People also ask

Which are the characteristics of entity class in JPA?

Entity PropertiesPersistability - An object is called persistent if it is stored in the database and can be accessed anytime. Persistent Identity - In Java, each entity is unique and represents as an object identity.

What are entities in JPA?

Entities in JPA are nothing but POJOs representing data that can be persisted to the database. An entity represents a table stored in a database. Every instance of an entity represents a row in the table.

What is the use of entity class in spring boot?

Entity: The entities are the persistence objects stores as a record in the database. Persistence Unit: It defines a set of all entity classes. In an application, EntityManager instances manage it. The set of entity classes represents the data contained within a single data store.


1 Answers

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.

like image 101
Piotr Kochański Avatar answered Oct 25 '22 06:10

Piotr Kochański