JPA,hibernate基于主键的一对一级联删除 10C

我希望删除user的时候,把cmscompany给级联删除掉。以下是我的代码,两实体是基于主键的一对一关系,级联删除一直删除不了,找了
很多资料,都没办法。求大神们帮帮忙

 //User实体
 import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;


@Entity
@Table(name="user")
public class User implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
    private CmsUserCompany cmsUserCompany;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @OneToOne(fetch = FetchType.LAZY, cascade = { CascadeType.ALL },mappedBy="user")
    public CmsUserCompany getCmsUserCompany() {
        return cmsUserCompany;
    }
    public void setCmsUserCompany(CmsUserCompany cmsUserCompany) {
        this.cmsUserCompany = cmsUserCompany;
    }
}
 import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;

import javax.persistence.Table;

@Entity
@Table(name="CmsUserCompany")
public class CmsUserCompany implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
    private User user;
    @Id
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @MapsId
    @OneToOne
    @JoinColumn(name="userid")
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}

3个回答

可以参考一下 http://blog.csdn.net/nthack5730/article/details/45366537 Hibernate基于主键一对一映射操作实例

yu766588220
花公子丶 用XML的倒是很简单,注解的删不了
3 年多之前 回复

两个实体类随便一个放弃外键执行权,使用另一个实体类的dao操作试试。。

yu766588220
花公子丶 怎么放弃外键执行权?我希望删除user的时候,cmscompany被级联删除
3 年多之前 回复

级联删除很危险,如果你一定要级联删除又不懂如何配置的话,我给你提供一个可行的方法,在service层,注入cmscompany的service,删除的时候,先删除cmscompany再删除user就可以了。删除cmscompany加个判断通过user的id就删除。不过要自己写一条hql

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐