Understanding transaction session with lazy loading in Spring JPA Hibernate

南楼画角 提交于 2019-12-05 20:51:22
wallenborn

With lazy loading, when you request an object a of type A, you get an object a of type A. a.getB() however, will not be of type B, instead a.getB() is a proxy for B that can be resolved later on (that's the lazy loading part), but only in the persistence context in which a lives in.

Your second implementation does just that: it resolves B by calling a.getB().getName() while you are still in the @Transaction. Hibernate can now make a second request to the database to fetch B, and now a.getB() is really of type B and stays that way, so you can use it outside the persistence context.

Your first implementation skips that. A is fetched from the database, the @Transactional block ends, then you call a.getB().getName(), but now the persistence context is gone, a.getB() can not be fetched from the database, and an exception is thrown.

What will happen if you add @Transactional(SUPPORTS) to LayerB ? Propagation SUPPORT means that method joins the caller’s transaction. By idea it will join the same transation LayerC created. And since LayerDB's getAForId method runs within same transaction that means they have same persitance context there should not be problem with fetching B name. I am just guessing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!