从附加父项中删除子节点

时间:2013-12-09 08:10:56

标签: java mysql hibernate

我有这样的父母:

@Entity
@Table(name="employee")
public class Employee implements Serializable {

@Id
@GeneratedValue()
@Column(unique=true, nullable=false)
private int id;

@OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER, targetEntity=Priority.class, orphanRemoval=true)
@IndexColumn(name="idx")
@JoinColumn(name="employee_id")
private List<Priority> priorities;

这样的儿童班:

@Entity
@Table(name="priority")
public class Priority implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private int id;

@Column(length=255)
private String focus;

@ManyToOne(optional=true)
@JoinColumn(name="employee_id", nullable=false)
private Employee employee;

我正在和父母一起工作。我想从父母那里读取,添加,编辑和删除优先级。我不想为自己更新每个更改。我想一次更新所有更改。 我所做的: 阅读员工并列出他的优先事项。现在我添加一个优先级,更改一个条目。 现在保存

utx.begin();
emp = em.merge(employee);
utx.commit();

添加,编辑和阅读工作正常,但在删除和保存时,我得到一个例外。

08:57:02,159 INFO  [stdout] (http-localhost-127.0.0.1-8080-1) Hibernate: update priority set employee_id=null, idx=null where employee_id=? and id=?
08:57:02,161 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-1) SQL Error: 1048, SQLState: 23000
08:57:02,162 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-1) Column 'employee_id' cannot be null
08:57:02,164 WARN  [com.arjuna.ats.arjuna] (http-localhost-127.0.0.1-8080-1) ARJUNA012125: TwoPhaseCoordinator.beforeCompletion - failed for SynchronizationImple< 0:ffff7f000101:3dfa0b66:52a577bb:11, org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization@438f8fc4 >: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Column 'employee_id' cannot be null

这个例外对我来说并不合适。我认为,hibernate doesent删除了orphant corectly whene我从父母那里移除了孩子,而它是附加的。

priority.setEmployee(null);
employee.getPriorities().remove(priority);

我尝试了不同的方法,但我得到了一个例外,或者它没有从数据库中删除它。

(顺便说一句,我使用MySQL作为数据库)

2 个答案:

答案 0 :(得分:0)

你从hibernate得到了正确的错误

当您将Employee employee注释为

@JoinColumn(name="employee_id", nullable=false)

这意味着Priority类的employee字段不应为null。

priority.setEmployee(空);

在此行上,您将员工设置为null并尝试违反您在优先级等级的员工字段中应用的 NOT NULL 约束

08:57:02,162 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-1) Column 'employee_id' cannot be null

你也提到过cascade={CascadeType.ALL}这意味着对父进行的任何操作都应该对子进行,所以当你删除Parent类时,这个父进程的所有相关子进程也会被删除,所以根据你的需要进行设置

答案 1 :(得分:0)

你可能想要的是inverse="true" cascade="all;delete-orphan"

相关问题