JPA无法在多对一关系中分配新的持久化实体

时间:2013-02-14 09:38:27

标签: spring hibernate 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.
}

在事务性Spring服务之后,我有下一个以这种方式操作实体的代码。

@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具有正确的值。 但我需要在交易中使用正确的值。

任何人都可以帮助我吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个

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