当插入/更新blob时,Hibernate使用两倍于文件大小的查询



我使用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).

我发现的唯一相关的帖子是从数据库加载26MB的文本数据,消耗258MB的JVM堆或与Postgre相关的帖子。有什么我可以修复我的代码,或者它是一个奇怪的怪癖,我需要知道吗?

编辑:我是要求保存文件在blob.

有没有办法在mysql数据库中插入一个大值而不改变max_allowed_packet?

如果你使用Preparedstatement和setBytes,那么双倍大小的问题是存在的,因为Mysql-Driver的行为会使大小加倍。请使用setBinaryStream。

您需要配置MySQL服务器来处理更大的数据包大小。有关更多信息,请参阅以下MySQL文档:http://dev.mysql.com/doc/refman/5.6/en/packet-too-large.html

最新更新