我有两个班级:
@Entity
@Table(name="Task_Monitor_Header")
@SequenceGenerator(name="INC_TASK_HEADER",sequenceName="GEN_TMH_ID")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Task {
@Id
@Column(name="tmh_id")
@GeneratedValue(strategy=GenerationType.AUTO,generator="INC_TASK_HEADER")
private Integer id = new Integer(0);
@ManyToMany
@Fetch(FetchMode.JOIN)
@Cascade({CascadeType.SAVE_UPDATE})
@JoinTable(name="task_equipment",
joinColumns=@JoinColumn(name="task_id"),
inverseJoinColumns=@JoinColumn(name="equipment_id"))
private Set<Equipment> equipments = new HashSet<Equipment>();
@OneToMany(mappedBy="task", targetEntity = TaskCondition.class, orphanRemoval=true)
@Fetch(FetchMode.JOIN)
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE_ORPHAN})
@OrderBy(value="seq")
private Set<TaskCondition> conditions = new HashSet<TaskCondition>();
...
}
和
@Entity
@Table(name="Task_Monitor_Items")
@SequenceGenerator(name="INC_TASK_ITEMS",sequenceName="GEN_TMI_ID")
@JsonIgnoreProperties(ignoreUnknown = true)
public class TaskCondition {
@Id
@Column(name="tmi_id")
@GeneratedValue(strategy=GenerationType.AUTO,generator="INC_TASK_ITEMS")
private int id;
@ManyToOne
@JoinColumn(name="tmi_task_id")
@JsonBackReference(value="conditions")
private Task task;
...
}
当我尝试在集合conditions
中添加或删除子节点,并调用hibernate save()
或saveOrUpdate()
时,它不会更改数据库状态但是,如果我执行了equipments
(@ManyToMany
)集合上的内容相同。
例如
public class TaskDaoImpl implements TaskDao {
@Autowired
private SessionFactory session;
@Override
public void edit(Task task, Authentication authentication) {
//Retrieve first child of Set
TaskCondition condition = task.getConditions().iterator().next();
//Remove that child
task.getConditions().remove(condition);
//Update the whole thing
session.getCurrentSession().saveOrUpdate(task);
}
}
有人可以帮助我吗?我已经尝试@CascadeType.DELETE_ORPHAN
,orphanRemoval=true
但没有成功。
答案 0 :(得分:3)
如果是双向关系,则必须从两个实体中删除引用:
task.getConditions().remove(condition);
condition.setTask(null);
同样适用于创建。
答案 1 :(得分:0)
感谢大家的回答,我发现了问题!
问题是Hibernate在删除之前,更新了FK列,将其设置为null
,在我的数据库中为NOT NULL
。
并将其更改为单向关系
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="tmi_task_id", referencedColumnName = "tmh_id")
@Cascade({CascadeType.SAVE_UPDATE})
private Set<TaskCondition> conditions;