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

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

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

映射文件如下:

  1. <hibernate-mapping>
  2. <class name="Customer" table="customers">
  3. <id name="id">
  4. <generator class="native"/>
  5. </id>
  6. <property name="name"/>
  7. <set name="orders" inverse="true">
  8. <key column="customer_id"/>
  9. <one-to-many class="Order"/>
  10. </set>
  11. </class>
  12. <class name="Order" table="orders">
  13. <id name="id">
  14. <generator class="native"/>
  15. </id>
  16. <property name="date"/>
  17. <many-to-one name="customer" column="customer_id"/>
  18. <list name="lineItems" table="line_items">
  19. <key column="order_id"/>
  20. <list-index column="line_number"/>
  21. <composite-element class="LineItem">
  22. <property name="quantity"/>
  23. <many-to-one name="product" column="product_id"/>
  24. </composite-element>
  25. </list>
  26. </class>
  27. <class name="Product" table="products">
  28. <id name="id">
  29. <generator class="native"/>
  30. </id>
  31. <property name="serialNumber"/>
  32. </class>
  33. </hibernate-mapping>

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

  1. create table customers (
  2. id BIGINT not null generated by default as identity,
  3. name VARCHAR(255),
  4. primary key (id)
  5. )
  6. create table orders (
  7. id BIGINT not null generated by default as identity,
  8. customer_id BIGINT,
  9. date TIMESTAMP,
  10. primary key (id)
  11. )
  12. create table line_items (
  13. line_number INTEGER not null,
  14. order_id BIGINT not null,
  15. product_id BIGINT,
  16. quantity INTEGER,
  17. primary key (order_id, line_number)
  18. )
  19. create table products (
  20. id BIGINT not null generated by default as identity,
  21. serialNumber VARCHAR(255),
  22. primary key (id)
  23. )
  24. alter table orders
  25. add constraint ordersFK0 foreign key (customer_id) references customers
  26. alter table line_items
  27. add constraint line_itemsFK0 foreign key (product_id) references products
  28. alter table line_items
  29. add constraint line_itemsFK1 foreign key (order_id) references orders