最近遇到了一個小的問題,就是怎么使用 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.com/a/1190000018843677