开发者

One to one mapping using primary key

开发者 https://www.devze.com 2023-04-09 07:29 出处:网络
I have two simple tables: Item and ItemDetail Table Item has following columns: id, name Table ItemDetail has following columns: itemId, color, size

I have two simple tables: Item and ItemDetail

Table Item has following columns: id, name

Table ItemDetail has following columns: itemId, color, size

An ItemDetail never exists without an Item. An Item can exist without any ItemDetail. For every Item there is at most one ItemDetail.

How should this situation be correctly mapped in hibernate?

So far I found only the following solution:

<class name="Item" table="Item">
    <id name="id" column="id">
        <generator class="native"></generator>
    </id>      
    <property name="name" />
    <one-to-one name="itemDetail" class="ItemDetail" cascade="save-update"/>
</class>

<class name="ItemDetail">
    <id name="itemId">
        <generator class="foreign">
            <param name="property">item</param>
        </generator>
    </id>
    <one-to-one name="item" class="Item" constrained="true" />
    <property name="color" />
    <property name="size" /> 
</class>

This solution works however I think it is not "clean" since in class ItemDetail I need to have both properties itemId and item.

private class Item {
  private long id;
  private String name;
  private ItemDetail detail;
}

private class ItemDetail {
  private long itemId;
  private Item item;
  private int color;
  private int size;
}

I think that from OOP perspective it is incorrect if object ItemDetail knows anything about Item. This means th开发者_开发知识库at it should not have properties itemId and item. Even if we agreed that it is correct if ItemDetail knows about Item, it is still incorrect that it has two references to Item - one using property itemId and one using property itemDetail. It can then very easily happen that these two properties are not synchronized. That is itemId references to different Item than the property item. To avoid this we would need to update both itemId and item everytime when we decide to set an Item to an ItemDetail.

Is there any other solution which does not have these drawbacks?

Thank you

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号