MySQL中Lob与JPA映射

本文介绍了MySQL中的Lob类型,包括Clob和Blob,用于存储大对象。Lob对象在JPA中通过@Lob注解进行映射,并可以自动转换为Clob或Blob类型。为了节省内存,通常使用延迟加载,配合FetchType.LAZY。MySQL的Lob对应字段类型有tinytext到longtext,可以根据需求选择。在Java中,Clob常与String对应,Blob与byte[]对应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • MySQL支持大量的列类型,它可以被分为3类:数字类型、日期和时间类型以及字符串(字符)类型。Mysql针对字符类型大对象存储的解决方案是Lob对象。

  • @Lob 注解属性将被持久化为 Blog 或 Clob 类型

  • Clob(Character Large Ojects)类型是长字符串类型,具体的java.sql.Clob, Character[], char[] 和 java.lang.String 将被持久化为 Clob 类型。
  • Blob(Binary Large Objects)类型是字节类型,具体的java.sql.Blob, Byte[], byte[] 和 serializable type 将被持久化为 Blob 类型。
  • @Lob 持久化为Blob或者Clob类型,根据get方法的返回值不同,自动进行Clob和Blob的转换。
  • 因为这两种类型的数据一般占用的内存空间比较大,所以通常使用延迟加载的方式,与@Basic标记同时使用,设置加载方式为FetchType.LAZY。

在MySQL中Blob和Clob对应的的字段类型有

  • tinytext (tintblob)
  • text (blob)
  • mediumtext (mediumblob)
  • longtext (longblob)

参考: MySQL中tinytext、text、mediumtext和longtext详解

一般在java中Clob类型用String声明,Blob用byte[]声明MySQL数据库对应字段,例如:

@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "f_task_content", nullable = false, columnDefinition = "Text")
private String taskContent;

Note that if you generate your table from the JPA annotations, you can "control" the type MySQL will use by specifying the length attribute of the Column, for example:

@Lob @Basic(fetch = FetchType.LAZY)
@Column(length=100000)
private byte[] picture;

It all depends on the column type used for the picture column. Depending on your needs, use a:

  • TINYBLOB: maximum length of 255 bytes
  • BLOB: maximum length of 65,535 bytes
  • MEDIUMBLOB: maximum length of 16,777,215 bytes
  • LONGBLOB: maximum length of 4,294,967,295 bytes

Depending on the length, you'll get:

   0 < length <=      255  -->  `TINYBLOB`
     255 < length <=    65535  -->  `BLOB`
   65535 < length <= 16777215  -->  `MEDIUMBLOB`
16777215 < length <=    2³¹-1  -->  `LONGBLOB`

reference:

[1]. https://blog.csdn.net/cnhome/article/details/42970253

[2]. https://www.jianshu.com/p/fadc24afe33c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值