使用两个外键创建复合唯一键

时间:2017-06-23 04:42:57

标签: hibernate jpa unique-constraint

我使用MySQL作为数据库并使用JPA并希望创建一个表quarter_level_result,其中我有两个外键,即quarter_iddepartment_id。我想设计表格,使这两个键的组合应该是唯一的。

所以我的代码是这样的:

@Entity
@Table(name = "quarter_level_result",
       uniqueConstraints= {@UniqueConstraint(
                                columnNames = {"quarter_id", "department_id"})})
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, 
                  property  = "id", 
                  scope     = Long.class)
@DynamicInsert(true)
@DynamicUpdate(true)
public class QuarterLevelResult implements Serializable {

    private static final long serialVersionUID = 6418708201861121181L;

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(optional = false )
    @JoinColumn(name = "quarter_id", unique = true)
    private QuarterLevel quarterLevel;

    @Transient
    private Long quarterId;

    @NotNull
    @Column(name = "current_level")
    private Long currentLevel;

    @NotNull
    @Column(name = "current_cost")
    private Long currentCost;

    @JoinColumn(name = "department_id", unique = true)
    @ManyToOne(optional = false)
    private Departments departmentInfoForQuarterResult;

    @Transient
    private Long departmentId;

    // getters and setters
}

问题:

最初我插入记录(quarter_id,department_id)=(1,2)它工作正常。之后,我插入了另一条记录(quarter_id,department_id)=(2,2)但是这种类型我得到了一个错误重复条目2为department_id。

1 个答案:

答案 0 :(得分:0)

只需从unique = true移除@JoinColumn:这是仅为该列创建唯一键的快捷方式。

@Table#uniqueConstraints就足够了。