24.3. Customer(客户)/Order(订单)/Product(产品)
优质
小牛编辑
132浏览
2023-12-01
现在来考虑
Customer
,Order
, LineItem
和 Product
关系的模型。Customer
和 Order
之间 是一对多的关系,但是我们怎么来描述 Order
/ LineItem
/ Product
呢? 我可以把 LineItem
作为描述 Order
和 Product
多对多关系的关联类,在 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_items
和 products
分别保存着 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