【发布时间】:2016-10-23 14:34:47
【问题描述】:
我有 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.Final User Guide 中表示
字节码增强的双向关联管理使第一个示例能够在任何一方被操纵时管理双向关联的“另一方”。
引用的“第一个示例”在哪里
示例 204. 不正确的正常 Java 用法
为什么在我的 test1 案例中,关联管理不起作用?我做错了什么?
【问题讨论】:
标签: java hibernate maven one-to-many bytecode