How to load the actual Hibernate entity association, not the LAZY proxy

I am coming from eclipselink and trying to work on my own through Hibernate.

Suppose we have a class Car and a class Wheel . Car class has n wheels. Both objects are associated with a bi-directional association. More importantly, on the Wheel side, I have a Car link:

 @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "car_id") private Car car; 

plus the recipient.

Now I want to get the wheel using its identifier. From my EntityManager (non-sleep mode Session ). I initialize the EntityManager as follows:

 EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); EntityManager em = emf.createEntityManager(); 

The next step is to select a wheel as follows:

 Wheel wheel = em.find(Wheel.class, 1); 

The wheel returns the desired class and its penalty. Now I want to know which car is the parent of the wheel with something like:

 Car car = wheel.getCar(); 

With eclipselink, the actual car would be loaded. Instead of hibernate, the proxy class is loaded instead.

The only solution I have developed so far is to install FetchType.EAGER or directly get the connection. I realized that the SQL statement in Hibernate is still executing, but no real object has been delivered. Also after

 Hibernate.initalize(car) 

I can not get the car.

Is there a way to return the expected object without generating a query or impatient fetch?

+6
source share
2 answers

You probably don't need to worry about proxies. The proxy server should return all properties in the same way as a regular object.

If the proxy object does not work (it returns zero values), perhaps some of your fields or setters or getters are set to final . Check this out first.

+6
source

You need to use the Hibernate LazyToOneOption.NO_PROXY annotation:

 @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "car_id") @LazyToOne(LazyToOneOption.NO_PROXY) private Car car; 

This will cause Hibernate to load the actual object instead of providing a proxy:

Lazy, return the real object loaded when the link was requested (Bytecode extension is mandatory for this option, return to PROXY if the class is not extended). This option should be avoided if you cannot afford to use proxies.

But to activate this option you will need to use the Bytecode toolkit.

+4
source

Source: https://habr.com/ru/post/982422/


All Articles