使用@ManyToMany JPA注释时不需要的唯一约束

时间:2016-07-19 07:28:21

标签: spring hibernate jpa

我正在为我的项目使用spring-boot / spring-data-jpa。当spring.jpa.hibernate.ddl-auto设置为更新时,下面的实体将在oracle中创建表。

@Entity
@Table(name = "SCENARIO")
public class Scenario {

    private Integer worksetId;
    private Integer ruleSetId;
    private Set<Rule> rules;

    @Id
    public Integer getWorksetId() {
        return worksetId;
    }

    public void setWorksetId(Integer worksetId) {
        this.worksetId = worksetId;
    }

    @Column(name = "RULE_SET_ID")
    public Integer getRuleSetId() {
        return ruleSetId;
    }

    public void setRuleSetId(Integer ruleSetId) {
        this.ruleSetId = ruleSetId;
    }

    @ManyToMany
    @JoinTable(name = "RULE_SET", joinColumns = @JoinColumn(name = "WORKSET_ID", referencedColumnName = "RULE_SET_ID"), inverseJoinColumns = @JoinColumn(name = "RULE_ID", referencedColumnName = "ID"))
    public Set<Rule> getRules() {
        return rules;
    }

    public void setRules(Set<Rule> rules) {
        this.rules = rules;
    }

}

@Entity
@Table(name = "RULE")
public class Rule {
    private Integer id;
    private String description;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

我期望的是创建SCENARIO / RULE表非常简单,以及名为RULE_SET的映射表。一切顺利,除了在表SCENARIO中创建RULE_SET_ID的不需要的唯一约束,但显然相同的RULE_SET_ID应该能够由多个场景共享。有人可以帮忙吗?非常感谢!!

BTW,我正在使用带有hibernate 5.0.9的spring-boot 1.4.0

1 个答案:

答案 0 :(得分:1)

显然,如果你做referencedColumnName = "RULE_SET_ID"RULE_SET_ID - 应该是唯一的。

您可以使用Scenario

的代理键
@Entity
@Table(name = "SCENARIO")
public class Scenario {

    @Id
    @GeneratedValue
    private Integer id;

}

并使用@ManyToMany映射

@ManyToMany
@JoinTable(name = "RULE_SET", joinColumns = @JoinColumn(name = "WORKSET_ID"), 
    inverseJoinColumns = @JoinColumn(name = "RULE_ID"))
public Set<Rule> getRules() {
    return rules;
}

<强>更新

我想将RuleSet实体用于一组规则(使用连接表进行maping):

@Entity
class RuleSet {

  @OneToMany
  private List<Rule> rules = new ArrayList<Rule>();

}