yagodkin
yagodkin

Reputation: 97

Hibernate entities mapping

I have entities Unit, Employee and I want have mapping to list of Employee in Unit.

Example 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

Now I have access to employees through 'nested' @OneToMany annotations:

In Unit:

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

Employee:

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

Upvotes: 0

Views: 251

Answers (1)

Jan Goyvaerts
Jan Goyvaerts

Reputation: 3033

I think by far the easiest solution would be to add a method to Unit:

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

and forget about mapping altogether.

Upvotes: 1

Related Questions