我正在尝试保存一个带有字节数组字段的实体。我在MySQL数据库上使用Hibernate和JPA。 这是字段定义,对于嵌入式H2数据库工作正常:
@Entity(name = "blob")
public class Blob {
...
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "blobImg", nullable = false)
private byte[] blobImg;
}
现在,使用MySQL数据库时,每次执行blobRepository.save()时都会抛出异常。实际上,在Hibernate尝试自动创建Blob实体表时可能会抛出该异常。该异常如下:
o.h.engine.jdbc.spi.SqlExceptionHelper : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'blob (blobCols, blobImg, blobRows, channel, idBlobPersistence) values (50, _bina' at line 1
我已尝试使用网络上找到的多种方法更改字段定义:
方法1:
@Column(name = "blobImg", nullable = false, columnDefinition = "BINARY(256)", length = 256)
private byte[] blobImg;
方法2:
@Lob
@Column(name="blobImg", columnDefinition="bytea")
private byte[] blobImg;
方案三:
在blob.hbm.xml文件中定义hibernate映射,并从entityManagerFactory bean引用它:
<?xml version='1.0' encoding='UTF-8'?>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="mappingResources">
<list>
<value>blob.hbm.xml</value>
</list>
</property>
</bean>
blob.hbm.xml映射:
<hibernate-mapping>
<class name="guiatv.persistence.domain.Blob" table="blob">
<property name="blobImgProperty">
<column name="blobImg" sql-type="binary"></column>
</property>
</class>
</hibernate-mapping>
方法四: 将blob.hbm.xml的映射更改为以下内容:
<?xml version='1.0' encoding='UTF-8'?>
<hibernate-mapping>
<class name="guiatv.persistence.domain.Blob" table="blob">
<property name="blobImg" type="binary">
<column name="blobImg" />
</property>
</class>
</hibernate-mapping>
所有的它们都抛出了相同的异常。
我该如何解决呢? 谢谢!
@Lob
:https://docs.oracle.com/javaee/7/api/javax/persistence/Lob.html -“Lob 类型是从持久字段或属性的类型推断出来的,除了字符串和字符类型以外,默认为 Blob。” - OndroMih