0

我有实体单位,员工,我想映射到单位中的员工列表。

示例 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;
    ...
}

位置到单位:

@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;
    ...
}
4

1 回答 1

1

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

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

完全忘记映射。

于 2013-03-22T13:50:31.930 回答