2013-12-09 59 views
0

I`ve删除孩子得了这样的家长:休眠从连接父

@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; 

I'm只是与父操作。我想读取,添加,编辑并从父项中移除优先级。我不想为自己更新每个更改。我想一次更新所有更改。 我的工作: 读一名员工并列出他的优先级。现在我添加一个优先级,更改一个条目。 现在用

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[email protected]438f8fc4 >: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Column 'employee_id' cannot be null 

这个例外对我来说并不敏感。我认为是这样的,休眠doesent删除大象真正的时候我把孩子从父母,而它被连接。

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

我试过不同的方法,但我得到一个异常或它不会从数据库中删除它。

(通过使用MySQL数据库的方式我真的)

+0

与您的问题混淆,您可以添加一些删除和保存员工优先级的代码 –

回答

0

您从休眠

得到正确的错误,当你注释Employee employee作为

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

这意味着雇员字段一个Priority类不应该为null。

priority.setEmployee(null);

在这条线要设置员工为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}作为优先级的员工领域NOT NULL约束它意味着任何操作对父母进行的操作应该对孩子进行,因此当您删除父类时,该父母的所有相关子条目也会被删除,因此根据您的需求进行设置

0

您想要的是inverse="true" cascade="all;delete-orphan"