23.1. Employer(雇主)/Employee(雇员)

下面关于EmployerEmployee的关系模型使用了一个真实的实体类 (Employment)来表述,这是因为对于相同的雇员和雇主可能会有多个雇佣时间段。 对于金额和雇员姓名,用Components建模。

23.1. Employer(雇主)/Employee(雇员) - 图1

映射文件可能是这样:

  1. <hibernate-mapping>
  2. <class name="Employer" table="employers">
  3. <id name="id">
  4. <generator class="sequence">
  5. <param name="sequence">employer_id_seq</param>
  6. </generator>
  7. </id>
  8. <property name="name"/>
  9. </class>
  10. <class name="Employment" table="employment_periods">
  11. <id name="id">
  12. <generator class="sequence">
  13. <param name="sequence">employment_id_seq</param>
  14. </generator>
  15. </id>
  16. <property name="startDate" column="start_date"/>
  17. <property name="endDate" column="end_date"/>
  18. <component name="hourlyRate" class="MonetaryAmount">
  19. <property name="amount">
  20. <column name="hourly_rate" sql-type="NUMERIC(12, 2)"/>
  21. </property>
  22. <property name="currency" length="12"/>
  23. </component>
  24. <many-to-one name="employer" column="employer_id" not-null="true"/>
  25. <many-to-one name="employee" column="employee_id" not-null="true"/>
  26. </class>
  27. <class name="Employee" table="employees">
  28. <id name="id">
  29. <generator class="sequence">
  30. <param name="sequence">employee_id_seq</param>
  31. </generator>
  32. </id>
  33. <property name="taxfileNumber"/>
  34. <component name="name" class="Name">
  35. <property name="firstName"/>
  36. <property name="initial"/>
  37. <property name="lastName"/>
  38. </component>
  39. </class>
  40. </hibernate-mapping>

SchemaExport生成表结构。

  1. create table employers (
  2. id BIGINT not null,
  3. name VARCHAR(255),
  4. primary key (id)
  5. )
  6. create table employment_periods (
  7. id BIGINT not null,
  8. hourly_rate NUMERIC(12, 2),
  9. currency VARCHAR(12),
  10. employee_id BIGINT not null,
  11. employer_id BIGINT not null,
  12. end_date TIMESTAMP,
  13. start_date TIMESTAMP,
  14. primary key (id)
  15. )
  16. create table employees (
  17. id BIGINT not null,
  18. firstName VARCHAR(255),
  19. initial CHAR(1),
  20. lastName VARCHAR(255),
  21. taxfileNumber VARCHAR(255),
  22. primary key (id)
  23. )
  24. alter table employment_periods
  25. add constraint employment_periodsFK0 foreign key (employer_id) references employers
  26. alter table employment_periods
  27. add constraint employment_periodsFK1 foreign key (employee_id) references employees
  28. create sequence employee_id_seq
  29. create sequence employment_id_seq
  30. create sequence employer_id_seq