0

我必须使用多对一的双向关系定义 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 已经有正确的值。但我需要交易中的正确值。

有谁能够帮我?先感谢您。

4

1 回答 1

0

尝试这个

@OneToMany(mappedBy="department",cascade = CascadeType.PERSIST)
private Set<Proffesor> proffesors;
于 2013-02-14T09:45:16.090 回答