2013-12-09 60 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"