23.2. Author(作家)/Work(作品)

考虑下面的Work,AuthorPerson模型的关系。 我们用多对多关系来描述WorkAuthor, 用一对一关系来描述AuthorPerson, 另一种可能性是Author继承Person

23.2. Author(作家)/Work(作品) - 图1

下面的映射文件正确的描述了这些关系:

  1. <hibernate-mapping>
  2. <class name="Work" table="works" discriminator-value="W">
  3. <id name="id" column="id">
  4. <generator class="native"/>
  5. </id>
  6. <discriminator column="type" type="character"/>
  7. <property name="title"/>
  8. <set name="authors" table="author_work">
  9. <key column name="work_id"/>
  10. <many-to-many class="Author" column name="author_id"/>
  11. </set>
  12. <subclass name="Book" discriminator-value="B">
  13. <property name="text"/>
  14. </subclass>
  15. <subclass name="Song" discriminator-value="S">
  16. <property name="tempo"/>
  17. <property name="genre"/>
  18. </subclass>
  19. </class>
  20. <class name="Author" table="authors">
  21. <id name="id" column="id">
  22. <!-- The Author must have the same identifier as the Person -->
  23. <generator class="assigned"/>
  24. </id>
  25. <property name="alias"/>
  26. <one-to-one name="person" constrained="true"/>
  27. <set name="works" table="author_work" inverse="true">
  28. <key column="author_id"/>
  29. <many-to-many class="Work" column="work_id"/>
  30. </set>
  31. </class>
  32. <class name="Person" table="persons">
  33. <id name="id" column="id">
  34. <generator class="native"/>
  35. </id>
  36. <property name="name"/>
  37. </class>
  38. </hibernate-mapping>

映射中有4个表。works, authorspersons 分别保存着work,author和person的数据。author_work是authors和works的关联表。 表结构是由SchemaExport生成的。

  1. create table works (
  2. id BIGINT not null generated by default as identity,
  3. tempo FLOAT,
  4. genre VARCHAR(255),
  5. text INTEGER,
  6. title VARCHAR(255),
  7. type CHAR(1) not null,
  8. primary key (id)
  9. )
  10. create table author_work (
  11. author_id BIGINT not null,
  12. work_id BIGINT not null,
  13. primary key (work_id, author_id)
  14. )
  15. create table authors (
  16. id BIGINT not null generated by default as identity,
  17. alias VARCHAR(255),
  18. primary key (id)
  19. )
  20. create table persons (
  21. id BIGINT not null generated by default as identity,
  22. name VARCHAR(255),
  23. primary key (id)
  24. )
  25. alter table authors
  26. add constraint authorsFK0 foreign key (id) references persons
  27. alter table author_work
  28. add constraint author_workFK0 foreign key (author_id) references authors
  29. alter table author_work
  30. add constraint author_workFK1 foreign key (work_id) references works