Spring Data JPA 建立表的联合主键

15次阅读

共计 1245 个字符,预计需要花费 4 分钟才能阅读完成。

最近遇到了一个小的问题,就是怎么使用 Spring Data JPA 建立表的联合主键?然后探索出了下面的两种方式。
第一种方式:
第一种方式是直接在类属性上面的两个字段都加上 @Id 注解,就像下面这样,给 stuNo 和 stuName 这两个字段加上联合主键:
@Entity
@Table(name = “student”)
public class Student {

@Id
@Column(name = “stu_no”, nullable = false, length = 11)
private Integer stuNo;

@Id
@Column(name = “stu_name”, nullable = false, length = 128)
private String stuName;

@Column(name = “stu_age”, nullable = false, length = 3)
private Integer stuAge;

@Column(name = “class_id”, nullable = false, length = 8)
private String classId;
}
只不过需要注意的是,实体类需要实现 Serializable 接口。
这种方式不是很好,虽然可以成功的创建表,但是使用 JpaRepository 的时候,需要指定主键 ID 的类型,这时候就会报错,所以使用第二种方式更好。
第二种方式:
实现起来也很简单,我们需要新建一个类,还是以 stuNo 和 stuName 建立联合主键,这个类需要实现 Serializable 接口。
public class StudentUPK implements Serializable {

private Integer stuNo;

private String stuName;

}
然后在实体类 Student 上面加上 @IdClass 注解,两个字段上面还是加上 @Id 注解:
@Entity
@IdClass(StudentUPK.class)
@Table(name = “student”)
public class Student {

@Id
@Column(name = “stu_no”, nullable = false, length = 11)
private Integer stuNo;

@Id
@Column(name = “stu_name”, nullable = false, length = 128)
private String stuName;

@Column(name = “stu_age”, nullable = false, length = 3)
private Integer stuAge;

@Column(name = “class_id”, nullable = false, length = 8)
private String classId;
}
这样就能成功的创建表了,而且在使用 JpaRepoistory 的时候,可以指定主键为那个 StudentUPK 类,就像这样:public interface StudentRepository extends JpaRepository<Student, StudentUPK>。

正文完
 0