Spring Data JPA 建立表的联合主键
Spring Data JPA 建立表的联合主键
https://www.jb51.net/article/159624.htm
最近遇到了一个小的问题,就是怎么使用 Spring Data JPA 建立表的联合主键?然后探索出了下面的两种方式。
第一种方式:
第一种方式是直接在类属性上面的两个字段都加上 @Id 注解,就像下面这样,给 stuNo 和 stuName 这两个字段加上联合主键:
?123456789101112131415161718 | @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; } |
1234567 | public class StudentUPK implements Serializable { private Integer stuNo; private String stuName; } |
12345678910111213141516171819 | @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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。