插入/更新blob时,Hibernate使用查询两次文件大小

时间:2015-05-23 15:59:51

标签: java mysql 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).

我发现的唯一相关帖子是Loading 26MB text data from database consume JVM heap of 258MB或与Postgre相关的帖子。有什么我可以解决我的代码或者它是一个我需要知道的奇怪的怪癖吗?

编辑:我必需将文件保存在blob中。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

Is there any way to insert a large value in a mysql DB without changing max_allowed_packet?

如果你使用Preparedstatement和那里有setBytes,那么问题就有了doublesize,因为Mysql-Driver的行为使这个大小增加了一倍。改为使用setBinaryStream。