我使用hibernate,从一个表到多个不同的表进行一对一的映射。
我有3个表Customer
, NormalCustomer
, PreviligedCustomer
。
CstId
是Customer
表中的主键,NormalCustomer
、PreviligedCustomer
表中的主键和外键。我有一个sql在这三个表上做左外连接,从三个表中获取不同的列值。
问题:NormalCustomer
/PreviligedCustomer
表第一次为空。这2张表将由其他进程更新。在Customer
obj上做了一些更新并保存后,创建了一个新的行NormalCustomer
和PreviligedCustomer
, Customer
的CstId
相同。
注意:对于Customer
表中的特定CstId
,存在一个或多个行
所需解决方案:我不希望一行被持久化在NormalCustomer
/PreviligedCustomer
表中,除非NormalCustomer
/PreviligedCustomer
中存在CstId
从Customer
的行。
映射: Customer.hbm.xml
<one-to-one name="NormalCustomer" class="com.test.NormalCustomer" cascade="save-update, merge"/>
<one-to-one name="PreviligedCustomer" class="com.test.PreviligedCustomer" lazy="false" fetch="join" cascade="save-update, merge"/>
NormalCustomer.hbm.xml
<one-to-one name="Customer" class="com.test.Customer" constrained="true" />
PreviligedCustomer.hbm.xml
<one-to-one name="Customer" class="com.test.Customer" constrained="true" />
我想有两种方法来处理这个问题:
-
你可以有条件地保存它们(手动)而不是使用'cascade= save - update '。
- 在这种情况下,您将首先保存客户实体和查询。
- 查询将检索现有的NormalCustomer/PrevilegedCustomer记录(如果有的话)。getNormalCustomer将显示记录(如果其他进程插入它)。
- 根据需要更新子对象
-
您可以继续使用save - update,但在初始保存客户实体检查您所需的条件之后。如果不满足,则从NormalCustomer/PrevilegedCustomer中删除新记录。