[英]Hibernate 5 Bytecode Enhancement Association Management works just in one direction
我有兩個這樣映射的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;
}
}
所有類都使用休眠增強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問題后,我了解到:
要觸發關聯管理,有時必須更改* ToMany字段,即使該字段具有相同的集合。 集合本身不會跟蹤更改。
因此,代替:
customer.getInventories().add( customerInventory );
需要調用設置器:
Collection<CustumerInventory> inventories = customer.getInventories();
inventories.add( customerInventory );
custumer.setInventories( inventories );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.