【发布时间】:2011-09-17 19:00:59
【问题描述】:
我想将一个具体的超类更改为其子类之一。我在下面提供了一个示例:
@Entity
@Table(name = "employees")
@Inheritance(strategy = InheritanceType.JOINED)
public class Employee {
@Id
@Column(name = "id")
private String id;
public Employee( String id ) {
this.id = id;
}
...
}
@Entity
@Table(name = "managers")
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
public class Manager extends Employee {
public Manager( String id ) {
super(id);
}
...
}
@Entity
@Table(name = "history")
public class History {
...
/**
*
*/
@ManyToOne
@JoinColumn(name = "employee_id")
private Employee employee;
...
}
我使用的三个类是员工、经理和历史。所有经理都是员工,但并非所有员工都是经理。所有员工(和经理)都有历史。员工可以晋升为管理层。发生这种情况时,应通过保持员工 ID 相同来保留员工的历史记录。这样可以轻松找到经理的就业历史。
由于数据库的约束,实现提升操作变得复杂:数据库不允许删除旧员工并创建具有相同 ID 的新经理,而无需通过级联操作删除所有历史对象 - 人力资源部不会允许,否则我的工作会很轻松!
是否可以在不借助自定义 SQL 操作的情况下添加或附加经理(新经理)行到现有员工?
我尝试了以下解决方案但没有成功:
public void promote( Employee employee ) {
/* copy over the ID of the employee to the manager. Will not work because employee with ID already exists */
Manager manager = new Manager(employee.getId());
this.entityManager.persist( manager );
}
...或...
public void promote( Employee employee ) {
/* detach the employee then merge. Will not work: fails, again, with a NonUniqueObject Exception */
this.entityManager.detach( employee );
Manager manager = new Manager(employee.getId());
this.entityManager.merge( manager );
}
我怎样才能完成这项工作? detach() 和 merge() 我是否走在正确的轨道上?
这在 Hibernate/JPA 中可行吗?
此时任何想法都会有所帮助,因为我很难过!
- 亚伦
【问题讨论】: