在Hibernate中使用mappedBy时保持Child实体

时间:2014-12-01 15:54:49

标签: hibernate jpa orm jpa-2.0 hibernate-onetomany

我的数据库架构有两个表: - Rule TableRule Scope表 规则表列(rule_id主键,.....)和规则范围列(rule_id外键,Scope_id非自动生成的ID,可以针对不同的rule_id重复
规则范围主键是rule_idScope_id的组合。

我的RULE实体

@Entity
@Table(name = "RULE")
public class Rule implements IEntity {

@Column(name = "RULE_ID")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int ruleId;

@OneToMany(fetch=FetchType.LAZY,mappedBy="rule")
private Set<RuleScope> ruleScope=new HashSet<RuleScope>();  

Rule Scope实体: -

@Entity
@Table(name = "RULE_SCOPE")
public class RuleScope {

@Embeddable
public static class Id implements Serializable{
    @Column(name = "RULE_ID")
    private int ruleId;
    @Column(name = "SCOPE_ID")
    private int scopeId;
}

@EmbeddedId
private Id id = new Id();

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "RULE_ID", insertable = false, updatable = false)
private Rule rule; 

我有以下问题: - 当我试图保存规则时,但它不是持久存在的子实体。当持久化违反外键约束的规则范围时,它为规则ID赋予0。但是当我使用@JoinColumn时,它正在运行。请在Rule Scope持续Rule并使用mappedBy时帮助我保留{{1}}。

1 个答案:

答案 0 :(得分:1)

试试这个:

规则实体:

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "RULE_ID", unique = true, nullable = false)
    private int ruleId;

    @OneToMany(mappedBy = "id.rule", cascade = CascadeType.ALL)
    private Set<RuleScope> ruleScope = new HashSet<RuleScope>(0);

    // Generate Getters, Setters, hashCode() and equals()
}

RULE_SCOPE实体:

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

    @EmbeddedId
    private Id id;

    // Generate Getters, Setters
}

RULE_SCOPE复合PK:

@Embeddable
public class Id implements Serializable {

    @ManyToOne
    @JoinColumn(name = "RULE_ID", , nullable = false)
    private Rule rule;

    @Column(name = "SCOPE_ID")
    private int scopeId;

    // Generate Getters, Setters, hashCode() and equals()
}