2013-02-14 64 views
0

我有一個雙向關係多對一,在此定義JPA實體:JPA無法在許多新的持久的實體分配到一個關係

@Entity 
public class Department implements Serializable { 
    private static final long serialVersionUID = 1L; 

    @Id 
    @SequenceGenerator(name="DEPARTAMENTO_ID_GENERATOR",sequenceName="DEPARTAMENTO_SEQ") 
    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="DEPARTAMENTO_ID_GENERATOR") 
    @Column(name="DEP_ID") 
    private long id; 

    @Column(name="DEP_DESC") 
    private String desc; 

    //bi-directional many-to-one association to Academico 
    @OneToMany(mappedBy="department") 
    private Set<Proffesor> proffesors; 
//getters and setters 
} 

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

    @Id 
    @SequenceGenerator(name="ACADEMICOS_ID_GENERATOR", sequenceName="ACADEMICOS_SEQ") 
    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="ACADEMICOS_ID_GENERATOR") 
    @Column(name="ACD_ID") 
    private long id; 
@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.MERGE}) 
    @JoinColumn(name="ACD_DEPADSCRITO_DEP") 
    private Department department; 
// getters and setters. 
} 

在事務春季服務後,我有下以這種方式操縱實體的代碼。

@Transactional (propagation=Propagation.REQUIRED) 
    public void createDepartmentWithExistentProffesor(String desc,Long idAvaiableProf) { 
     // new department 
     Department dep = new Department(); 
     dep.setDesc(desc); 
     HashSet<Proffesor> proffesors = new HashSet<Proffesor>(); 
     dep.setProffesors(proffesors); 


// I obtain the correct attached Proffesor entity 
     Proffesor proffesor=DAOQueryBasic.getProffesorById(idAvaiableProf); 

// I asign the relationship beetwen proffesor and department in both directions 
       dep.addProffesors(proffesor); 
// Persists department  
     DAODataBasic.insertDepartment(dep); 
// The id value is not correct then Exception ORA-0221 
     System.out.println("SERVICIO: Departamento creado con id: " + dep.getId()); 

    } 

正如我在新部門的ID堅持的評論說的是不是在事務內部實際的數據庫ID,那麼就產生一個異常

Exception in thread "main" org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update 
........ 

Caused by: java.sql.BatchUpdateException: ORA-02291: integrity restiction (HIBERNATE_PRB.FK_ACD2DEP) violated - primary key don't found 

我已經在測試試,堅持新的離職者實體與Proffesor沒有關係,我已經看到新部門堅持實體的id在交易中沒有有效的價值,但是在交易之外,該id已經具有正確的價值。 但我需要交易中的正確值。

任何人都可以幫助我嗎? 預先感謝您。

回答

0

試試這個

@OneToMany(mappedBy="department",cascade = CascadeType.PERSIST) 
private Set<Proffesor> proffesors; 
+0

謝謝,我嘗試過,但不起作用。 – 2013-02-14 15:14:49

+0

你有沒有試過合併教授而不是堅持新的部門。我知道這不合乎邏輯。但值得一試。之後** Proffesor proffesor = DAOQueryBasic.getProffesorById(idAvaiableProf); **執行此操作** proffesor.setDepartment(department); entityManager.merge(教授); ** 看看它是否會工作。 – spiritwalker 2013-02-14 23:17:44

+0

在閱讀你的評論之前,我做了它,但還沒有工作。再次感謝您的幫助。 – 2013-02-15 09:02:29