JPA之映射mysql text類型
問題背景
jpa如果直接映射mysql的text/longtext/tinytext類型到String字段會報錯。需要設置一下@Lob和@Column。
@Lob代表是長字段類型,默認的話,是longtext類型,所以需要下面這個屬性來指定對應的類型。
columnDefinition="text"里面的類型可以隨意改,后面mysql可能會有新的類型,只要是對應java的String類型,就可以在這里動態配置。
解決方案
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Data @Entity @Table (name= "question" ) public class Question { @Id @GeneratedValue public int questionId; //....省略其他字段 @Lob @Column (columnDefinition= "text" ) public String explainStr; public Date createTime; } |
JPA各種類型映射處理
1.日期格式類型字段的映射,利用@Temporal(TemporalType.Date)進行注解;例如:
1
2
3
4
5
6
7
8
|
private Date birthday; @Temporal (TemporalType.DATE) public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this .birthday = birthday; } |
2.枚舉類型的映射,利用@Enumerated,其參數EnumType表示指定存放在數據表中的形式,整型還是String;
首先創建一個枚舉:
1
2
3
4
|
public enum Gender { Male,Female } |
在實體類中調用:
1
2
3
4
5
6
7
8
|
private Gender gender = Gender.Male; // 為枚舉設置默認值 @Enumerated (EnumType.STRING) public Gender getGender() { return gender; } public void setGender(Gender gender) { this .gender = gender; } |
3.大文本數據類型的映射,例如:網絡日志,字符串類型的長度顯然不夠,利用@Lob注解,該注解用在字符串類型之上在數據庫生成LongText類型的數據;例如:
1
2
3
4
5
6
7
8
|
private String diary; @Lob public String getDiary() { return diary; } public void setDiary(String diary) { this .diary = diary; } |
4.@Lob注解用在Byte[]數組類型,例如:保存一個文件可以用此類型,用在這個上面在數據庫中可以生成LongBolb數據類型;例如:
1
2
3
4
5
6
7
8
|
private Byte[] file; @Lob public Byte[] getFile() { return file; } public void setFile(Byte[] file) { this .file = file; } |
5.如果在實體類中不需要該字段與數據庫中的表進行映射,但是默認的情況下是將實體類的全部字段映射成數據表的列,那該怎樣做呢?利用@Transient注解,例如:
1
2
3
4
5
6
7
8
|
private String other; @Transient public String getOther() { return other; } public void setOther(String other) { this .other = other; } |
6.如果一個實體類中包含一個大數據類型的字段,如Byte[]類型,當我們查詢該實體類時不得不查詢出該數據類型的字段,如果我們在查詢時只用到一個其它字段的數據,但是默認情況下是查詢全部的,那該怎樣避免查詢該大數據類型的數據呢?利用@Basic注解進行標注,將fetch屬性值設置為Lazy即可,這樣只有在我們調用該屬性的get方法時才會進行加載;
1
2
3
4
5
6
7
8
|
private Byte[] file; @Lob @Basic (fetch=FetchType.LAZY) public Byte[] getFile() { return file; } public void setFile(Byte[] file) { this .file = file; } |
7.@Column 該注解表示數據表的映射列,放在屬性的getter方法上:
-
.length
:該屬性表示該映射列的長度; -
.nullable
:該屬性表示該列是否可為空,true表示可為空,false表示不可為空; -
.name
:該屬性表示為該列起別名,不讓實體類的屬性名與數據庫的列名相同;
8.@Table 該注解表示映射的表;放在該實體類之上:
-
.name
:該屬性表示為表起別名,讓實體類與數據表名不相同;
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://zhengkai.blog.csdn.net/article/details/82143590