JPA在更新时删除记录

时间:2013-11-20 11:51:29

标签: jpa membership delete-record

有人可以帮我解决以下情况吗?

我有一个要求,当孩子与任何其他父记录没有关联时,我需要删除会员记录和子表。我只需要分离会员记录。

我正在使用JPA Eclipse链接...

以下是我的三个实体..请注意,Parent和Child通过Parent_Child多对多关系链接。我在两边都使用Parent_Child表,因为我们有额外的列..

//父

@Entity
@Table(name = "PARENT")
public class Parent implements java.io.Serializable {

    @Id
    @Column(name = "parent_id")
    private String parentId;

    private Set<ParentChild> parentChildSet = new HashSet<ParentChild>(0);



    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent")
    public Set<ParentChild> getParentChildSet() {
        return parentChildSet;
    }

    public void setParentChildSet(Set<ParentChild> parentChildSet) {
        this.parentChildSet = parentChildSet;
    }
}

//子

    @Entity
    @Table(name = "CHILD")
    public class Child  implements java.io.Serializable {


        private String ChildId;

        private Set<ParentChild> parentChildSet = new HashSet<ParentChild>(0);

        @Id
        @Column(name = "child_id")
        public String getChildId() {
            return ChildId;
        }

        public void setChildId(String childId) {
            ChildId = childId;
        }

        @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "child")
        public Set<ParentChild> getParentChildSet() {
            return parentChildSet;
        }

        public void setParentChildSet(Set<ParentChild> parentChildSet) {
            this.parentChildSet = parentChildSet;
        }
}

//父子

@Entity
@Table(name = "PARENT_CHILD")
public class ParentChild implements java.io.Serializable{

    private String parentChildId;

    private Parent parent;

    private Child child;

    @Id
    @Column(name = "parent_child_id")
    public String getParentChildId() {
        return parentChildId;
    }

    public void setParentChildId(String parentChildId) {
        this.parentChildId = parentChildId;
    }

    public Parent getParent() {
        return parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }

    public Child getChild() {
        return child;
    }

    public void setChild(Child child) {
        this.child = child;
    }
}

关系:父母 - Praent_Child(一对多)                Child - Parent_Child(一对多)

我正在尝试按以下方式执行...但是,它给了我完整性约束异常,因为我正在删除子项然后更新父级

public void ParentChildServiceDAO{
........
.........

    if(parentChildSet().size() > 1){
        parent.getParentChildSet().remove(parentChildRecord);
        child.getParentChildSet().remove(parentChildRecord);
    } else{
        parent.getParentChildSet().remove(parentChildRecord);
        child.getParentChildSet().remove(parentChildRecord);
        getJpaTemplate().remove(child);
    }

    update(parent);

} 

非常感谢您的帮助......

0 个答案:

没有答案