我有一个类Person
和一个包含三个类的类层次结构,当我将 InheritanceType.TABLE_PER_CLASS 用于类层次结构时,它遇到了“批量更新”问题。请看下面的代码。AbstractBase
是类层次结构的基类。
public class Person {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
@OneToMany
@JoinColumn(name="Employee_employees_Person", referencedColumnName = "id")
@Cascade({org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE})
private Set<Employee> employees = new HashSet<>();
}
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@javax.persistence.Access(javax.persistence.AccessType.FIELD)
public abstract class AbstractBase {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
@Entity
@Table(name = "EmployeeClass")
@javax.persistence.Access(javax.persistence.AccessType.FIELD)
public class Employee extends AbstractBase implements Serializable {
private String name;
@Column(name="Employee_employees_Person")
private String Employee_employees_Person_ID;
}
@Entity
public class Manager extends Employee {
@Property(name="ManagerLevel")
@Column(name="ManagerLevel")
private String level;
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
}
测试代码:
em.getTransaction().begin();
Person a = new Person();
Employee e1 = new Employee();
e1.setName("Bill");
Manager m1 = new Manager();
m1.setName("Amanda");
m1.setLevel("VP");
a.getEmployees().add(e1);
a.getEmployees().add(m1);
em.persist(a);
em.getTransaction().commit();
输出:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1"
Manager
我通过hibernate sql发现Hibernate没有更新表。当我将 InheritanceType 更改为 时InheritanceType.JOINED
,代码运行良好。我错过了单向一对多配置中的某些内容吗?
- - - - - - - - - - - - - - - - - 更新 - - - - - - - - -----------------
在“Person”类中,我在一对多注释中将@JoinColumn 更改为@JoinTable,测试代码运行良好。当@JoinColumn 的目标类被“InheritanceType.TABLE_PER_CLASS”注解时,是否有遗漏配置?
请看下面的详细注释:
@OneToMany
//@JoinColumn(name="Employee_employees_Person", referencedColumnName = "id")
@JoinTable (
name = "Person_employees_Employee",
joinColumns={ @JoinColumn(name="Person_ID", referencedColumnName="id") },
inverseJoinColumns={ @JoinColumn(name="Employee_ID", referencedColumnName="id", unique=true)}
)
@Cascade({org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE})
private Set<Employee> employees = new HashSet<>();
- - - - - - - - - - - - - - - - - - -更新 - - - - - - --------------------
我用 Hibernate 5.2.5 Final 尝试了代码,问题仍然存在。