[英]How to work unique key constraint with JPA annotations in my springboot project?
How to work multi-column constraint with JPA annotations in my springboot project?如何在我的 springboot 项目中使用 JPA 注释进行多列约束? I'm trying to introduce a multi-key constraint on a JPA-mapped entity:我正在尝试在 JPA 映射实体上引入多键约束:
@Entity
@Table(name = "Student_Master",uniqueConstraints={
@UniqueConstraint(columnNames = {"id","sr_no.", "roll_no"})
})
public class StudentMaster implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer sId;// id same
@Column(name = "sr_no.", length = 5,nullable = false,unique = true)//not null and sr no. should be unique
private Integer srNo;
@Column(name = "roll_no", length = 10,nullable = false,unique = true)
private Integer rollNo;
Basically (id, sr_no,roll_no)
pair should be unique, but I only found a way to say that id should be unique.基本上(id, sr_no,roll_no)
对应该是唯一的,但我只找到了一种说 id 应该是唯一的方法。
I have also declare unique constraints using the @Table(uniqueConstraints =...)
annotation in your entity class.我还在您的实体 class 中使用@Table(uniqueConstraints =...)
注释声明了唯一约束。
But it's didn't work because entry the duplicate roll no and srNo also with different user.但它不起作用,因为输入重复的卷号和 srNo 也与不同的用户。
You have the option to create an Embedded class
, which contains your keys and reference it in your StudentMaster
您可以选择创建Embedded class
,其中包含您的密钥并在StudentMaster
中引用它
For this you need @EmbeddedId
in your Entity and @Embeddable
over your key class:为此,您需要在您的实体中使用@EmbeddedId
并在您的密钥@Embeddable
上使用 @Embeddable:
@Embeddable
public class MyKey implements Serializable {
@Column(name = "id")
private Integer sId;// id same
@Column(name = "sr_no.", length = 5, nullable = false, unique = true)//not null and sr no. should be unique
private Integer srNo;
@Column(name = "roll_no", length = 10, nullable = false, unique = true)
private Integer rollNo;
/** getters and setters **/
}
@Entity
public class StudentMaster implements Serializable {
@EmbeddedId
private MyKey myKey;
}
Or a way without having the embedded class you can use @IdClass(MyKey.class)
.或者没有嵌入式 class 的方法,您可以使用@IdClass(MyKey.class)
。 Now you can use the @Id
over your key attributes现在您可以在关键属性上使用@Id
public class MyKey implements Serializable {
private Integer sId;
private Integer srNo;
private Integer rollNo;
/** getters and setters **/
}
@Entity
@IdClass(MyKey.class)
public class StudentMaster implements Serializable {
@Id
@Column(name = "id")
private Integer sId;// id same
@Id
@Column(name = "sr_no.", length = 5, nullable = false, unique = true)//not null and sr no. should be unique
private Integer srNo;
@Id
@Column(name = "roll_no", length = 10, nullable = false, unique = true)
private Integer rollNo;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.