我有 3 个表:customer、rent 和 edition。客户有一个或多个租金,版本有一个或多个租金。租金有 2 个外键 (customerId, editionId) 和一个主键 (rentId),我正在尝试删除一位客户,但我有一个错误,即 customerId 的 fk 仍在租金表中。我首先从客户的listRent 中删除所有租金。这是删除方法(电子邮件是来自rent's表的customerId):
public boolean delete(String email){
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("tutorial");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Customer customer= entityManager.find(Customer.class, email);
if(customer!=null){
entityManager.getTransaction().begin();
for (Rent rent :customer.getRentList()) {
entityManager.remove(rent);
}
entityManager.remove(customer);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
return true;
}
entityManager.close();
entityManagerFactory.close();
return false;
}
但仍然有错误:
javax.persistence.RollbackException: Error while committing the transaction (...)
Caused by: org.postgresql.util.PSQLException: ERROR: update o delete in «customer» violates the foreign key «fkgft5yuturjnobc97u2x1464b» in the table «rent»
这里是客户实体:
@Entity
@Table(name="Customer")
public class Customer {
@Id
@Column(name="email")
private String email;
@Column(name="firstName")
private String firstName;
@Column(name="lastName")
private String lastName;
@Column(name="Gender")
private String gender;
@Column(name="age")
private Integer age;
@OneToMany(mappedBy = "customer", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Rent> rentList = new ArrayList<>();
public Customer(){
}
public Customer(String email, String firstName, String lastName, String gender, Integer age) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.age = age;
}
和出租实体:
@Entity
@Table(name = "Rent")
public class Rent {
@Id
@GeneratedValue
@Column(name="rent_id")
private Integer rentId;
@ManyToOne
@JoinColumn(name="email")
private Customer customer;
@ManyToOne
@JoinColumn(name="edition_id")
private Edition edition;
@Column(name="renting_date")
private String rentingDate;
public Rent(){
}
public Rent(String rentingDate) {
this.rentingDate = rentingDate;
}
我跳过编辑表只是因为与具有其他属性的客户相同,并且两个表的所有者都是租用的。我尝试直接在 postgresql 中删除并在我删除租用表然后删除客户表时工作,但由于某种原因,我不能用 jpa 删除
我使用的是 postgresql 13、wildfly 23 和 hibernate。
答案 0 :(得分:0)
在 Hibernate(https://github.com/hibernate/hibernate-orm/blob/main/hibernate-core/src/test/java/org/hibernate/test/bytecode/enhancement/cascade/CascadeDeleteCollectionTest.java) 中有一些测试正好可以练习这个场景,所以你的设置肯定有问题。由于您在 Wildfly 上运行,因此手动构建 EntityManagerFactory
有点可疑。我的猜测是,您正在将自定义的旧版本 Hibernate 打包到您的 WAR 中,然后使用它可能有问题。尝试使用 <scope>provided</scope>
作为 Hibernate 依赖项。