JPA“无法转换为 java.sql.Blob”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5222218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:02:58  来源:igfitidea点击:

JPA "cannot be cast to java.sql.Blob"

javahibernateblobjpa-2.0derby

提问by suicide

I'm using JPA2 with hibernate 3.6.1. and a Derby database and I used the following annotation for a blob:

我在 Hibernate 3.6.1 中使用 JPA2。和一个 Derby 数据库,我对 blob 使用了以下注释:

@Column(length = Integer.MAX_VALUE)
@Lob
long[] bucket;

Hibernate creates the correct blob column but if I try to save an entity I get the following exception:

Hibernate 创建了正确的 blob 列,但是如果我尝试保存实体,则会出现以下异常:

java.lang.ClassCastException: [J cannot be cast to java.sql.Blob

java.lang.ClassCastException: [J 不能转换为 java.sql.Blob

why and how can I make this work?

为什么以及如何进行这项工作?

If I annotate it without the @Lob I get a "Varchar for bit data" column which can only contain up to 32m.

如果我在没有@Lob 的情况下对其进行注释,则会得到一个“位数据的 Varchar”列,该列最多只能包含 32m。

回答by Augusto

You need to map the property as a byte[], not as long[].

您需要将属性映射为 byte[],而不是 long[]。

The documentationsays

文件说:

@Lob indicates that the property should be persisted in a Blob or a Clob depending on the property type: java.sql.Clob, Character[], char[] and java.lang.String will be persisted in a Clob. java.sql.Blob, Byte[], byte[] and serializable type will be persisted in a Blob.

If the property type implements java.io.Serializable and is not a basic type, and if the property is not annotated with @Lob, then the Hibernate serializable type is used.

@Lob 表示该属性应该保存在 Blob 或 Clob 中,具体取决于属性类型:java.sql.Clob、Character[]、char[] 和 java.lang.String 将保存在 Clob 中。java.sql.Blob、Byte[]、byte[] 和可序列化类型将被持久化到一个 Blob 中。

如果属性类型实现了java.io.Serializable 并且不是基本类型,并且属性没有用@Lob 注释,则使用Hibernate 可序列化类型。

If you want to persist the array, you'll need to build a custom user type to transform the data type. You can find an example here http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#d0e2794

如果要保留数组,则需要构建自定义用户类型来转换数据类型。你可以在这里找到一个例子http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#d0e2794