2014-12-01 78 views
0

我的數據庫模式有兩個表: - Rule TableRule Scope表。
規則表中的列(rule_id主鍵,.....)和規則範圍列(rule_id外鍵,Scope_id不能自動生成的ID,可以重複用於不同RULE_ID
規則範圍的主鍵的組合rule_id以及Scope_id在Hibernate中使用mappedBy時持久子實體

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

+0

您是否嘗試過:@OneToMany(的mappedBy =「rule」,fetch = FetchType.LAZY) private設置 ruleScope = new HashSet (); – 2014-12-01 16:13:51

+0

它給出了同樣的例外 – 2014-12-01 16:55:19

+0

我目前使用OpenJPA,並不能很有幫助。我會嘗試ManyToMany,PrimaryKeyJoinColum或JOIN策略....您可以稍後再查看,然後將其更改回來。 – 2014-12-01 22:00:52

回答

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() 
} 
+0

感謝您的更新..我糾正,它開始工作。我使用了不同的方法.. – 2014-12-07 16:27:18

相關問題