Persisting Child entity when using mappedBy in Hibernate

572 views Asked by At

My DB schema has two tables :- Rule Table and Rule Scope table.
Rule Table columns (rule_id Primary Key, .....) and Rule Scope columns (rule_id Foreign key , Scope_id (NOT Auto generated Id, Can repeat for different rule_id)
Rule Scope Primary key is combination of rule_id and Scope_id.

My RULE Entity

@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:-

@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; 

I have following questions:-
When I am trying to save the Rule , but it is not persisting the Child Entity. it is giving 0 for Rule Id when persisting the Rule Scope which is violating the Foreign Key Constraint. But when i use @JoinColumn the it is working. Please help me to persist the Rule Scope while persisting Rule and using mappedBy.

1

There are 1 answers

1
Chazar On

Try this:

Rule Entity:

@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:

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

    @EmbeddedId
    private Id id;

    // Generate Getters, Setters
}

RULE_SCOPE composite 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()
}