[英]DTO to JPA Entity in onetomany bidirectional relationship with orika
[英]delete entity in onetomany relationship jpa
我有 3 个表:客户、租金和版本。 其中客户有一个或多个租金,并且版本有一个或多个租金。 租金有 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。
Hibernate中有测试( https://github.com/hibernate/hibernate-orm/blob/main/hibernate-core/src/test/java/org/hibernate/test/bytecode/enhancement/cascade/CascadeDeleteCollectionTest.Z93F725A0742331C889Z448B )这正是这种情况,所以你的设置一定有问题。 自从在 Wildfly 上运行以来,手动构建EntityManagerFactory
有点可疑。 我猜,您正在将自定义旧版本的 Hibernate 打包到您的 WAR 中,然后使用它可能有问题。 尝试对 Hibernate 依赖项使用<scope>provided</scope>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.