Empty Join Table resulting from JPA ManyToMany

时光总嘲笑我的痴心妄想 提交于 2019-12-05 07:30:47

I found the problem. It is a bit weird. The DAO class that I was using had a class level annotation of:

@Transactional(readOnly=true)

The sql generated was

Hibernate: insert into CAMERAS (CAMERA_BRAND) values (?)
Hibernate: insert into LENSES (LENS_NAME) values (?)
Hibernate: insert into LENSES (LENS_NAME) values (?)

And still it saved the 2 entities, but did not save or insert data into the join table.

The moment I added a method level annotation of :

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)

everything turned out to be fine, and data was indeed inserted into the join table. The new SQLs generated in this case was...

Hibernate: insert into CAMERAS (CAMERA_BRAND) values (?)
Hibernate: insert into LENSES (LENS_NAME) values (?)
Hibernate: insert into LENSES (LENS_NAME) values (?)

Hibernate: insert into CAMERAS_LENSES (CAM_ID, LENS_ID) values (?, ?)
Hibernate: insert into CAMERAS_LENSES (CAM_ID, LENS_ID) values (?, ?)

Kinda weird still that no transaction propogation strategy saved data into 2 tables, but once the propogation strategy was given, everything turned out to be fine.

Another interesting observation is that I tried putting the propogation strategy as MANDATORY at the method level (to check if there existed a Transaction which led to the first and faulty case), however the method threw an exception indicating that no transaction existed, still the data was saved into the 2 tables.

Hope that helps someone further on...

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