站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Hibernate reference 3.2.0 ga 正式版中文参考手册

23.3. Customer(客户)/Order(订单)/Product(产品) - Hibernate reference 3.2.0 ga 正式版中文参考手册

23.3. Customer(客户)/Order(订单)/Product(产品)

现在来考虑Customer,OrderLineItemProduct关系的模型。CustomerOrder之间 是一对多的关系,但是我们怎么来描述Order / LineItem / Product呢? 我可以把LineItem作为描述OrderProduct 多对多关系的关联类,在Hibernate,这叫做组合元素。

映射文件如下:

<hibernate-mapping>

    <class name="Customer" table="customers">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <set name="orders" inverse="true">
            <key column="customer_id"/>
            <one-to-many class="Order"/>
        </set>
    </class>

    <class name="Order" table="orders">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="date"/>
        <many-to-one name="customer" column="customer_id"/>
        <list name="lineItems" table="line_items">
            <key column="order_id"/>
            <list-index column="line_number"/>
            <composite-element class="LineItem">
                <property name="quantity"/>
                <many-to-one name="product" column="product_id"/>
            </composite-element>
        </list>
    </class>

    <class name="Product" table="products">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="serialNumber"/>
    </class>

</hibernate-mapping>

customers, orders, line_itemsproducts 分别保存着customer, order, order line item 和 product的数据。 line_items也作为连接orders 和 products的关联表。

create table customers (
    id BIGINT not null generated by default as identity, 
    name VARCHAR(255), 
    primary key (id)
)

create table orders (
    id BIGINT not null generated by default as identity, 
    customer_id BIGINT, 
    date TIMESTAMP, 
    primary key (id)
)

create table line_items (
    line_number INTEGER not null, 
    order_id BIGINT not null, 
    product_id BIGINT, 
    quantity INTEGER, 
    primary key (order_id, line_number)
)

create table products (
    id BIGINT not null generated by default as identity, 
    serialNumber VARCHAR(255), 
    primary key (id)
)

alter table orders 
    add constraint ordersFK0 foreign key (customer_id) references customers
alter table line_items
    add constraint line_itemsFK0 foreign key (product_id) references products
alter table line_items
    add constraint line_itemsFK1 foreign key (order_id) references orders