gpt4 book ai didi

java - 删除具有关系的实体

转载 作者:行者123 更新时间:2023-11-30 04:31:38 25 4
gpt4 key购买 nike

我有下一个实体。 CarHuman 具有多对多关系。我在 CarUser

之间使用辅助类 Assign
@Entity
public class Car implements Serializable
{
//...

@LazyCollection(LazyCollectionOption.TRUE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "car")
private Set<Assign> cars = new HashSet<Assign>();
//...
}

@Entity
class Assign implements Serializable
{
//...

@LazyCollection(LazyCollectionOption.FALSE)
@ManyToOne
@JoinColumn(name = "HUMAN_CAR", nullable = false)
private Human human;

@LazyCollection(LazyCollectionOption.FALSE)
@ManyToOne
@JoinColumn(name = "CAR_HUMAN", nullable = false)
private Car car;
//..

}

@Entity
public class Human implements Serializable
{
//...

@LazyCollection(LazyCollectionOption.TRUE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "human")
private Set<Assign> cars = new HashSet<Assign>();
// ...
}

现在我尝试删除容器内的汽车管理事务

   public void deleteCar(final long id)
{
final Car car = entityManager.find(roleId, Car.class);
entityManager.remove(car);
}

但我明白了

Caused by: javax.persistence.EntityNotFoundException: deleted entity passed to persist: [com.dto.Assign#<null>]

最佳答案

在删除Car之前删除Assign-s

public void deleteCar(final long id)
{
final Car car = entityManager.find(roleId, Car.class);
for(Assign assign : car.getAssigns()) {
entityManager.remove(assign);
}
entityManager.remove(car);
}

您的 getter 可能有不同的名称,我看不到该代码。

关于java - 删除具有关系的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com