Hibernate code…exception in onetoone mapping

余生长醉 提交于 2019-12-05 18:50:30

I faced similar situation and resolved it myself after some experimentation. An important thing to remember here is that when you use foreign strategy for an ID generator the relationship can't be unidirectional. In your case you need to make two changes(see below).Basically you have set cascade to all for AddressVO @OneToOne(cascade=CascadeType.ALL) and when you try to save the UserVO this will trigger similar operation for AddressVO. But for AddressVO you set the Id generator strategy as 'foreign' with property userVO. But you never set the property userVO in AddressVO so it gets null id and hence the exception. To make this work for you need to do the following changes

1) Add userVO property (getter/setters) to AddressVo and before saving userVo add this object to addressVO in you transaction address.setUserVo(user); and then call session.save(user);

2)Edit your db schema to reflect the shared primarykey in addressVO as the foreign key constraint is in AddressVo not in UserVO. i.e., change the following

alter table mediashow_user1 
add index FK5FD5BCE8801495D (empid), 
add constraint FK5FD5BCE8801495D 
foreign key (empid) 
references mediashow_address1 (empid)

to

alter table mediashow_address1 
add index FK5FD5BCE8801495D (empid), 
add constraint FK5FD5BCE8801495D 
foreign key (empid) 
references mediashow_user1 (empid)

If you want to make this work for Unidirection one-to-one relation ship then you should handle the cascade operations yourself. Basically you should do the following

1)Remove the foreign key strategy (Just use @Id and @column annotations for empId in AddressVO with out any @GeneratedValue).

2)Remove the cascade options for AddressVo in your UserVO (as this will trigger similar operations on AddressVO and the id is still not known)

3)Set the empId for AddressVo before saving this address. You should use the id that you obtain when you save userVo.

Long id= (Long)session.save(user);
address.setEmpid(id);
session.save(address)

basically you should handle the save/update/delete operations for addresss too.

Hope this explanation helps :)

Make this change in your code :

 @GenericGenerator(name="foreign", strategy = "foreign", parameters={
 @Parameter(name="property", value="user")
 })

we need to pass object of the class instead of class name in parameter annotation in its value parameter. Hence there should not be value="userVO" and should be value="user"

Please try and let me know if it works

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