Hibernate实体映射

时间:2013-03-22 10:59:59

标签: java hibernate one-to-many

我有实体Unit,Employee,我想要映射到Unit中的Employee列表。

示例SQL:

select e.*
from wfm.WFM_EMPLOYEE e
    join wfm.wfm_position2unit p2u on p2u.UNIT_POSITION_ID=e.unit_position_id
    join wfm.WFM_POSITION p on p.POSITION_ID=p2u.POSITION_ID
    join wfm.wfm_unit u on u.UNIT_ID=p2u.UNIT_ID
where u.unit_id = 337

现在我可以通过'嵌套'@OneToMany注释访问员工:

单位:

@Entity
@Table(name = "WFM_UNIT", schema = AppData.WFM_SCHEMA)
public class Unit implements Serializable {
    ...
    @OneToMany(mappedBy = "unit", fetch = FetchType.EAGER)
    private List<Position2unit> position2units;
    ...
}

PositionToUnit:

@Entity
@Table(name = "WFM_POSITION2UNIT", schema = AppData.WFM_SCHEMA)
public class Position2unit implements Serializable {
    ...
    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "POSITION_ID")
    private Position position;

    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "UNIT_ID")
    private Unit unit;

    @OneToMany(mappedBy = "position2unit", fetch = FetchType.LAZY)
    private List<Employee> employees;
    ...
}

员工:

@Entity
@Table(name = "WFM_EMPLOYEE", schema = AppData.WFM_SCHEMA)
public class Employee implements Serializable {
    ...
    @NotFound(action = NotFoundAction.IGNORE)
    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "UNIT_POSITION_ID")
    private Position2unit position2unit;
    ...
}

1 个答案:

答案 0 :(得分:1)

我认为到目前为止最简单的解决方案是向Unit添加一个方法:

Collection<Employee> getEmployees() {
  final Collection<Employee> employees = new HashSet<Employee>();
  for (final Position2unit p2u : position2units) {
    employees.addAll(p2u.employees);
  }
  return employees;
}

并完全忘记了映射。