|
I encountered some inconsistent behaviour of meta data validation, processed during EntityManager construction which is related to the specification of bidirectional associations. Consider following code, consisting of a 1:n-relationship between Department and Employee and a 1:1-relationship between Employee and SystemAccount.
@Entity
public class Department {
@OneToMany(mappedBy = "department")
private Set<Employee> employees;
}
@Entity
public class Employee {
@ManyToOne
private Department department;
@ManyToMany
private Set<Skill> skills;
@OneToOne
private SystemAccount account;
}
@Entity
public class SystemAccount {
@OneToOne(mappedBy = "account")
private Employee employee;
}
@Entity
public class Skill {
}
We agree that the associations specified are valid, right?
Let's now change the mappedBy attribute of the @OneToOne annotation of SystemAccount.employee from "account" to "skills". Apart from the fact that the referred entity's types are inconsistent, the EM construction throws the following exception:
Unable to build Hibernate SessionFactory: Referenced property not a (One|Many)ToOne: p.Employee.skills in mappedBy of p.SystemAccount.employee
I am very happy with this message, since the inverse side of a @OneToOne association should be a @OneToOne association or at most a @ManyToOne association.
Instead of this change, let's now change the mappedBy-attribute of the @OneToMany association of Department.employees from "department" to "skills". From my point of view, the situation is very similar to the first change: We have a mappedBy-attribute of a @OneTo... association end referring to a field, annotated with one of the @...ToMany associations. However, the entity manager can be constructed successfully without throwing any exception or warning.
Running through the 12 possible constellations, I get the following results (The lines representing a field having the specified annotation including a mappedBy attribute, the columns representing the annotation of the targeted field):
|
|
@OneToOne
|
@ManyToOne
|
@OneToMany
|
@ManyToMany
|
|
|
|
|
|
|
|
@OneToOne
|
OK
|
OK
|
rejected
|
rejected
|
|
@OneToMany
|
OK
|
OK
|
not rejected
|
not rejected
|
|
@ManyToMany
|
not rejected
|
not rejected
|
OK
|
OK
|
There are four cases which, from my point of view, should be rejected but which are accepted by Hibernate. Is there a reason for this?
|