我使用MySQL作为数据库并使用JPA并希望创建一个表quarter_level_result
,其中我有两个外键,即quarter_id
和department_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。
答案 0 :(得分:0)
只需从unique = true
移除@JoinColumn
:这是仅为该列创建唯一键的快捷方式。
@Table#uniqueConstraints
就足够了。