The hibernate documentation says: "the constructor should be defined with at least package visibility if you wish to leverage runtime proxy generation". I've read in the hibernate documentation, that hibernate can enhance bytecode instead of proxy creation(Hibernate 5.x). It can substitute the proxy creation with this new method in every cases? In which cases do I need runtime proxy generation?
1 Answers
Runtime enhancement is the default, it is used for lazy loading support. If you want to use lazy loading on a @OneToOne
or @ManyToOne
association then the class which will be lazily loaded should have a protected constructor or else Hibernate will throw an exception when you attempt to fetch the parent entity. So for example:
@Entity
public class Parent {
@OneToOne(fetch=FetchType.LAZY)
private Child child;
}
In this example the Child
class must have a constructor with protected or greater visibility.
With Hibernate 5.0 you can do bytecode enhancement. This is an extra compilation step, so you will need to place it in your Maven or Ant (or whatever) build process. With bytecode enhancement you should not need to no-arg constructor but if you don't include it your application will not be adhering to the JPA spec (only important if you plan on switching to some provider other than Hibernate).

- 41,875
- 13
- 113
- 156