在OneToMany关系中删除

时间:2017-12-01 17:19:57

标签: java entity-framework hibernate jpa

我创建了两个实体Employee和Position。我有从Employee到Position的单向OneToMany关系,即Position实体包含员工过去数据的记录。我有员工班

@Entity
@Table(name = "EMPLOYEES")
@Audited
public class Employee extends BaseEntity {

    private static final long serialVersionUID = 9025203354200600861L;

    @Id
    @Column(name = "EMPLOYEE_NUMBER")
    private Integer employeeNumber; 

    @OneToMany(targetEntity = Position.class, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(joinColumns=@JoinColumn(name="EMPLOYEE_ID"),
              inverseJoinColumns=@JoinColumn(name="POSITION_ID"))
    private List<Position> position;

public List<Position> getPosition() {
    return position;
}

public void setPosition(List<Position> position) {
    this.position = position;
}
}

我有dao注射删除功能:

 @Inject 
    PositionDao positionDao;

/.../
public void deletePosition(){
        positionDao.delete(positionDao.getEntityById(3));
    }

删除功能使用实体管理器删除功能:

  public void delete(T t) {
    em.remove(t);
}

由于关系是一对多,我必须能够删除from位置实体。但是当我尝试执行删除时,它会将异常视为:

The DELETE statement conflicted with the REFERENCE constraint "FK1fygqmvwtna26i9cisuavevo". The conflict occurred in database "Research", table "dbo.EMPLOYEES_POSITIONS", column 'POSITION_ID'.

Employee Table

Position Table

Intermediate Table Generated from the relationship

员工表 位置表 中间表从关系中生成

0 个答案:

没有答案