sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Spring Data JPA 建立表的联合主键
https://www.jb51.net/article/159624.htm

最近遇到了一个小的问题,就是怎么使用 Spring Data JPA 建立表的联合主键?然后探索出了下面的两种方式。

第一种方式:

第一种方式是直接在类属性上面的两个字段都加上 @Id 注解,就像下面这样,给 stuNo 和 stuName 这两个字段加上联合主键:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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 的类型,这时候就会报错,所以使用第二种方式更好。

第二种方式:

Java技术迷

实现起来也很简单,我们需要新建一个类,还是以 stuNo 和 stuName 建立联合主键,这个类需要实现 Serializable 接口。

1
2
3
4
5
6
7
public class StudentUPK implements Serializable {
 
  private Integer stuNo;
 
  private String stuName;
 
}

然后在实体类 Student 上面加上 @IdClass 注解,两个字段上面还是加上 @Id 注解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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> 。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

posted on 2022-03-05 22:41  sunny123456  阅读(523)  评论(0编辑  收藏  举报