1.关系的拥有者:规范24页
The inverse side of a bidirectional relationship must refer to its owning side by use of the
mappedBy element of the OneToOne, OneToMany,or ManyToMany annotation. The
mappedBy element designates the property or field in the entity that is the owner of the rela-
tionship.
使用mappedBy的实体称为被控方。
@Entity public class Cubicle { private Employee residentEmployee; @OneToOne(mappedBy="assignedCubicle") public Employee getResidentEmployee() { return residentEmployee; } public void setResidentEmployee(Employee employee) { this.residentEmployee = employee; } ... }
例如上面,Cubicle是被控方,而Employee是主控方,是关系的拥有者。
官方的一对多双向的写法:Collection
@Entity public class Employee { private Department department; @ManyToOne public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } ... } @Entity public class Department { private Collection<Employee> employees = new HashSet(); @OneToMany(mappedBy="department") public Collection<Employee> getEmployees() { return employees; } public void setEmployees(Collection<Employee> employees) { this.employees = employees; } ... }
2.mappedBy的位置
The many side of one-to-many / many-to-one bidirectional relationships must be the owning
side, hence the mappedBy element cannot be specified on the ManyToOne annotation.
一对多和多对一双向关系中多方是关系的拥有者,因此mappedBy不能在ManyToOne中。
3.cascade=REMOVE 的位置
The cascade=REMOVE specification should only be applied to associations that are specified as One-
ToOne or OneToMany. Applications that apply cascade=REMOVE to other associations are not por-
table.
cascade=REMOVE 只能在OneToOne or OneToMany的声明中使用。
4.PERSIST的含义:
• If X is a new entity, it becomes managed. The entity X will be entered into the database at or
before transaction commit or as a result of the flush operation.
如果实体X是新创建的,他将变成被托管状态下的bean,那么persist之后X将在事务提交或flush操作之后存入数据库。
• If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist
operation is cascaded to entities referenced by X, if the relationships from X to these other
entities is annotated with the cascade=PERSIST or cascade=ALL annotation element
value or specified with the equivalent XML descriptor element.
如果X是已经存在的被托管bean,则将persist忽略。但是persist对X级联PERSIST/ALL的实体起作用。
• If X is a removed entity, it becomes managed.
如果X是以及被删除的状态,他将变成被托管状态。
• If X is a detached object, the EntityExistsException may be thrown when the persist
operation is invoked, or the EntityExistsException or another PersistenceEx-
ception may be thrown at flush or commit time.
如果X已经被废弃,则persit将发生异常。
• For all entities Y referenced by a relationship from X, if the relationship to Y has been anno-
tated with the cascade element value cascade=PERSIST or cascade=ALL, the persist
operation is applied to Y.
5.EAGER和LAZY默认场合
@OneToOne和@ManyToOne默认是EAGER的加载方式
@OneToMany和@ManyToMany默认是LAZY的加载方式