我使用 MySQL 和 Hibernate 将上传的文件保存在数据库中。文件被转换为字节数组作为简单实体的字段:
@Entity
@Table(name = "TestBlob")
public class TestBlob {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Lob
@Column(name = "file")
private byte[] file;
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
}
然后当我尝试运行以下代码时:
@Override
public void addBlob(TestBlob t) {
System.out.println("Trying to upload file with size:" + t.getFile().length);
Session session = sessionFactory.getCurrentSession();
session.save(t);
}
@Override
public void updateBlob(TestBlob t) {
System.out.println("Trying to upload file with size:" + t.getFile().length);
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(t);
}
我得到这个输出:
Trying to upload file with size:8663040
Hibernate:
insert
into
TestBlob
(file)
values
(?)
...
com.mysql.jdbc.PacketTooBigException: Packet for query is too large (17326125 > 16777216).
我找到的唯一相关帖子是 Loading 26MB text data from database consume JVM heap of 258MB或与 Postgre 相关的帖子。我的代码有什么可以修复的地方,还是我需要知道一些奇怪的怪癖?
编辑:我需要将文件保存在 blob 中。
最佳答案
Is there any way to insert a large value in a mysql DB without changing max_allowed_packet?
如果您使用Preparedstatement并且有setBytes,那么就会出现doublesize的问题,因为Mysql驱动程序的行为会使大小加倍。请改用 setBinaryStream。
关于java - Hibernate 在插入/更新 blob 时使用两倍文件大小的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30414763/