我的要求是在数据库中存储图像数组。在存储该图像数组时,Hibernate 会抛出异常 GenericJDBCException
和大量堆栈跟踪,然后由:com.mysql.jdbc.PacketTooBigException:查询数据包太大
引起。我的要求是当遇到 PacketTooBigException
时增加数据库的数据包查询大小。因此,我采用了两个 catch block catch(PacketTooBigException e){...}
和 catch (Exception e){..}
。
但是 Hibernate 不会像 JDBC 那样直接抛出 PacketTooBigException。 Hibernate 首先抛出 GenericJDBCException
,然后抛出 Caused by: com.mysql.jdbc.PacketTooBigException:
。为了克服这种情况,我在 catch block 中编写了 if(e.getCause().getClass() == PacketTooBigException.class){..my job..}
。
1)我的方向正确吗?
2)或者任何人都可以建议我更好的方法,以便我可以直接捕获PacketTooBigException
。
感谢您抽出时间。
最佳答案
正如您正确分析的那样, hibernate 将原始数据库异常(exception)包装为原因。
问题是捕获这样的异常是否有意义。我不知道您的业务领域,但通常 PacketTooBigException 意味着您正在尝试存储一个与 blob 一样大的文件。
此类问题最好在验证时处理。要么将允许的最大大小增加
SET GLOBAL max_allowed_packet = <some big value>
并在上传文件时进行验证。
更新:
根据 mysql 文档,增加所有查询的限制是安全的(通过更改变量或编辑 my.ini)。
http://dev.mysql.com/doc/refman/5.5/en/packet-too-large.html
引用上面的链接:
It is safe to increase the value of this variable because the extra memory is allocated only when needed. For example, mysqld allocates more memory only when you issue a long query or when mysqld must return a large result row. The small default value of the variable is a precaution to catch incorrect packets between the client and server and also to ensure that you do not run out of memory by using large packets accidentally.
但即使将其增加到新的最大值,您仍然会面临上传更大文件的风险,因此最好对用户界面本身进行验证检查。
关于java - catch PacketTooBigException() block 在 Hibernate 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27565594/