JPA之映射mysql text类型的问题

网友投稿 2190 2022-12-01

JPA之映射mysql text类型的问题

JPA之映射mysql text类型的问题

目录JPA之映射mysql text类型问题背景解决方案JPA各种类型映射处理

JPA之映射mysql text类型

问题背景

jpa如果直接映射mysql的text/longtext/tinytext类型到String字段会报错。需要设置一下@Lob和@Column。

@Lob代表是长字段类型,默认的话,是longtext类型,所以需要下面这个属性来指定对应的类型。

columnDefinition="text"里面的类型可以随意改,后面mysql可能会有新的类型,只要是对应java的String类型,就可以在这里动态配置

解决方案

@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)进行注解;例如:

private Date birthday;

@Temporal(TemporalType.DATE)

public Date getBirthday() {

return birthday;

}

public void setBirthday(Date birthday) {

this.birthday = birthday;

}

2.枚举类型的映射,利用@Enumerated,其参数EnumType表示指定存放在数据表中的形式,整型还是String;

首先创建一个枚举:

public enum Gender

{

Male,Female

}

在实体类中调用:

private Gender gender = Gender.Male; // 为枚举设置默认值

@Enumerated(EnumType.STRING)

public Gender getGender() {

return gender;

}

public void setGender(Gender gender) {

this.gender = gender;

}

3.大文本数据类型的映射,例如:网络日志,字符串类型的长度显然不够,利用@Lob注解,该注解用在字符串类型之上在数据库生成LongText类型的数据;例如:

private String diary;

@Lob

public String getDiary() {

return diary;

}

public void setDiary(String diary) {

this.diary = diary;

}

4.@Lob注解用在Byte[]数组类型,例如:保存一个文件可以用此类型,用在这个上面在数据库中可以生成LongBolb数据类型;例如:

private Byte[] file;

@Lob

public Byte[] getFile() {

return file;

}

public void setFile(Byte[] file) {

this.file = file;

}

5.如果在实体类中不需要该字段与数据库中的表进行映射,但是默认的情况下是将实体类的全部字段映射成数据表的列,那该怎样做呢?利用@Transient注解,例如:

private String other;

@Transient

public String getOther() {

return other;

}

public void setOther(String other) {

this.other = other;

}

6.如果一个实体类中包含一个大数据类型的字段,如Byte[]类型,当我们查询该实体类时不得不查询出该数据类型的字段,如果我们在查询时只用到一个其它字段的数据,但是默认情况下是查询全部的,那该怎样避免查询该大数据类型的数据呢?利用@Basic注解进行标注,将fetch属性值设置为Lazy即可,这样只有在我们调用该属性的get方法时才会进行加载;

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:该属性表示为表起别名,让实体类与数据表名不相同;

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:D. Epic Transformation
下一篇:C++11并发学习之五:生产者与消费者
相关文章

 发表评论

暂时没有评论,来抢沙发吧~