好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

JPA之映射mysql text类型的问题

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

查看更多关于JPA之映射mysql text类型的问题的详细内容...

  阅读:14次