我有2个JPA实体像这样映射:
@MappedSuperclass
public class AbstractEntity {
private static final String INCREMENT_STRATEGY = "increment";
private static final String INCREMENT_ID_GENERATOR_NAME = "INCREMENT_ID_GENERATOR";
@Id
@GenericGenerator(name = INCREMENT_ID_GENERATOR_NAME, strategy = INCREMENT_STRATEGY)
@GeneratedValue(generator = INCREMENT_ID_GENERATOR_NAME)
private Long id;
public AbstractEntity() {
super();
}
public Long getId() {
return id;
}
}
@Entity
public class Department extends AbstractEntity{
@OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
private List<Employee> employees = new ArrayList<Employee>();
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public List<Employee> getEmployees() {
return employees;
}
}
@Entity
public class Employee extends AbstractEntity {
@ManyToOne(optional = true, cascade= CascadeType.ALL)
@JoinColumn(name = "DEPARTMENT_ID")
private Department department;
public void setDepartment(Department department) {
this.department = department;
}
public Department getDepartment() {
return department;
}
}
所有类都使用hibernate增强maven插件进行字节码增强:
<build>
<plugins>
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>5.2.2.Final</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
</dependencies>
<configuration>
<enableDirtyTracking>true</enableDirtyTracking>
<enableLazyInitialization>true</enableLazyInitialization>
<enableAssociationManagement>true</enableAssociationManagement>
</configuration>
</plugin>
</plugins>
</build>
我运行两个测试来验证增强类是否正常工作:
@Test
public void test1() {
Department department = new Department();
Employee employee = new Employee();
department.getEmployees().add(employee);
assertThat(employee.getDepartment(), is(not(nullValue())));
}
@Test
public void test2() {
Department department = new Department();
Employee employee = new Employee();
employee.setDepartment(department);
assertThat(department.getEmployees().size(), is(1));
assertThat(department.getEmployees().get(0), is(employee));
}
只有第二个测试成功通过,因此当关联通过父节点的集合操作时,子节点的父节点字段没有更新,而在Hibernate ORM 5.2.3中。最终用户指南
字节码增强的双向关联管理通过管理"另一边"使第一个示例工作。当一方被操纵时,双向关联的。
此处引用"第一个例子";
204。错误的正常Java用法
为什么在我的test1的情况下,关联管理不工作?我做错了什么?
在单元测试中,可能会发生类没有增强的情况,特别是当您在IDE中运行它们时。
确保增强的类包含在您在进行测试的项目中导入的不同模块中。
或者您可以运行增强过程,验证类已被增强,然后再运行单元测试。
总而言之,我猜您可能正在运行实体类的未增强版本。
无论如何,我不认为这个功能真的是必要的。同步关联的两端是可行的方法,它只需要您提供addChild和removeChild方法。跟踪Andrei的JIRA问题,我了解到:
来触发关联管理,在某些情况下必须有* many字段的更改,即使它与相同的集合。不跟踪集合本身的更改。
所以,而不是:
customer.getInventories().add( customerInventory );
需要调用setter:
Collection<CustumerInventory> inventories = customer.getInventories();
inventories.add( customerInventory );
custumer.setInventories( inventories );