Skip to content
Advertisement

Hibernate 5 and JPA: select table without his children but maintain persistence on save

I have two models: Ordine and DettaglioOrdine. I would like that, when I save an object of type “Ordine”, hibernate also save his child “DettaglioOrdine” (and this works). But, if I do a select query, the query is very very slow because hibernate retrieve also DettaglioOrdine. So, I would like the “Ordine” object without “DettaglioOrdine” object.

“Ordine” model:

JavaScript

DettaglioOrdine Model:

JavaScript

And this is my query:

JavaScript

Advertisement

Answer

It is not Hibernate. You have fetch=FetchType.LAZY for dettagliordine. Hibernate doesn’t have to fetch the lazy association with the parent.

The problem can be here

JavaScript

if the code inside unmarshall() method touches dettagliordine or invoke a method, that differs from get, set methods (like toString() method), Hibernate will fetch dettagliordine association.

You can enable Hibernate logging and debug the code. You will see when fetching actually happens. Also keep in mind, if you debug persistent classes, the debugger can cause invoking of toString() method and the association will be fetched too.

Better to move this line outside session/@Transactional block of code.

JavaScript

You will have LazyInitializationExcepton, with any unwanted access to lazy associations.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement