最近遇到了一个小的问题,就是怎么使用 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 的类型,这时候就会报错,所以使用第二种方式更好。
第二种方式:
实现起来也很简单,我们需要新建一个类,还是以 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> 。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://segmentfault测试数据/a/1190000018843677
查看更多关于Spring Data JPA 建立表的联合主键的详细内容...