我的数据库架构有两个表: - Rule Table
和Rule Scope
表
规则表列(rule_id
主键,.....)和规则范围列(rule_id
外键,Scope_id
(非自动生成的ID,可以针对不同的rule_id重复)
规则范围主键是rule_id
和Scope_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}}。
答案 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()
}