2013-02-14 61 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