广告
返回顶部
首页 > 资讯 > 数据库 >JPA之映射mysql text类型的问题
  • 279
分享到

JPA之映射mysql text类型的问题

2024-04-02 19:04:59 279人浏览 八月长安
摘要

目录JPA之映射Mysql text类型问题背景解决方案JPA各种类型映射处理JPA之映射mysql text类型 问题背景 jpa如果直接映射mysql的text/longtext

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

您可能感兴趣的文档:

--结束END--

本文标题: JPA之映射mysql text类型的问题

本文链接: https://www.lsjlt.com/news/154506.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作