使用Hibernaet存储MYSQL表中BLOB字段的有关问题
org.hibernate.exception.SQLGrammarException: could not insert: [cn.com.servyou.bbs.domain.Image] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2186) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2666) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:562) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:550) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:546) 。。。 Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: 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 '$T??ú2{??÷?#M`9;? ¤?2?tJp>1?÷D?<???Pm?òQ?mn?????Nè\'?.89??4… .?\'U\0??0?' at line 1 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1051) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3562) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3494) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1960) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2114) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2696) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2105) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2398) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2316) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2301) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57) ... 17 more
在网上查阅了很多资料,自己也经过测试,使用纯JDBC代码进行测试,发现了这样一个问题。
用纯JDBC代码是可以将图片的二进制流存入数据库表的相应字段的。如果是用Hibernate存储CLOB字段是没有问题的,但是在存储BLOB字段时会出现问题。
错误可能的原因:
1. 使用了MYSQL 的保留字作为表字段名
2. 字符集的问题,需要在Hibernate配置文件中,对数据库连接URL指定编码
jdbc:mysql://127.0.0.1:3306/hibernate_demo?useUnicode=true&characterEncoding=utf-8
先给出数据库脚本及配置。。。
数据库表创建脚本:
create table t_test( id int(11) not null auto_increment, photo mediumblob, primary key(id) )
Hibernate配置文件:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 显示实际操作资料库时的SQL --> <property name="show_sql">true</property> <!-- 格式化SQL --> <property name="format_sql">true</property> <!-- SQL方言,这边设定的是MySQL --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- JDBC驱动程式 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- JDBC URL --> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate_demo</property> <!-- 数据库使用者 --> <property name="connection.username">root</property> <!-- 数据库密码 --> <property name="connection.password">123456</property> <property name="hbm2ddl.auto">none</property> <!-- 加入二级缓存 --> <!-- <property name="hibernate.cache.use_query_cache">true</property> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> --> <!-- C3P0连接池配置 --> <property name="c3p0.min_size">5</property> <property name="c3p0.max_size">20</property> <property name="c3p0.timeout">1800</property> <property name="c3p0.max_statements">50</property> <!-- 以下设置物件与资料库表格映射文件 --> <mapping resource="cn/com/servyou/bbs/domain/Image.hbm.xml" /> </session-factory> </hibernate-configuration>
Image映射配置文件:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="cn.com.servyou.bbs.domain.Image" table="t_test"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native" /> </id> <property name="blob" column="photo" type="java.sql.Blob"></property> </class> </hibernate-mapping>
为了便于大家理解这里给出HibernateSessionFactory和FileUtil的代码,HibernateSessionFactory主要是将session与当前使用的线程进行绑定:
HibernateSessionFactory:
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static String CONFIG_FILE_LOCATION = "hibernate-cfg.xml"; private static SessionFactory sessionFactory; static { Configuration conf = new Configuration() .configure(CONFIG_FILE_LOCATION); sessionFactory = conf.buildSessionFactory(); } public static Session getSession() { Session session = threadLocal.get(); if (null == session) { if (null == sessionFactory) { Configuration conf = new Configuration() .configure(CONFIG_FILE_LOCATION); sessionFactory = conf.buildSessionFactory(); } session = sessionFactory.openSession(); threadLocal.set(session); } return session; } public static void closeSession() { Session session = threadLocal.get(); threadLocal.set(null); if (null != session && session.isOpen()) { session.close(); } } }
FileUtil(想必也没什么好解释的了哈):
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class FileUtil { public static byte[] getBytes(String path) { BufferedInputStream bis = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { bis = new BufferedInputStream(new FileInputStream(path)); byte[] bytes = new byte[8096]; int index; while ((index = bis.read(bytes)) != -1) { byteArrayOutputStream.write(bytes, 0, index); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != bis) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != byteArrayOutputStream) { try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return byteArrayOutputStream.toByteArray(); } public static void writeFile(InputStream inputStream, String destFilePath) { BufferedOutputStream bos = null; BufferedInputStream bis = null; try { bos = new BufferedOutputStream(new FileOutputStream(destFilePath)); bis = new BufferedInputStream(inputStream); byte[] buffer = new byte[8096]; int index = -1; while ((index = bis.read(buffer)) != -1) { bos.write(buffer, 0, index); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != bos) try { bos.close(); } catch (IOException e) { e.printStackTrace(); } if (null != bis) try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
使用JDBC代码测试,观察能否将图片二进制流存入数据库(我本机的“D:\\My Documents\\My Pictures\\”目录下放了一个20090731124506989.jpg图片,可以自行指定):
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import cn.com.servyou.bbs.util.FileUtil; public class WriteAndReadImage { public static Connection getConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/hibernate_demo", "root", "xxxxxx"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static void writeImage() throws IOException, SQLException { Connection conn = getConnection(); PreparedStatement ps = (PreparedStatement) conn .prepareStatement("insert into t_test(photo) values (?)"); File imgFile = new File( "D:\\My Documents\\My Pictures\\20090731124506989.jpg"); InputStream inputStream = new FileInputStream(imgFile); byte[] bytes = FileUtil .getBytes("D:\\My Documents\\My Pictures\\20090731124506989.jpg"); ps.setBinaryStream(1, inputStream, (int) imgFile.length()); ps.setBytes(1, bytes); int flag = ps.executeUpdate(); System.out.println(flag); } public static void readImage() throws IOException, SQLException { Connection conn = getConnection(); PreparedStatement ps = conn .prepareStatement("select photo from t_test"); ResultSet rs = ps.executeQuery(); int count = 1; while (rs.next()) { Blob blob = rs.getBlob("photo"); InputStream inputStream = blob.getBinaryStream(); FileUtil.writeFile(inputStream, "D:\\a"+count+++".jpg"); } } public static void main(String[] args){ //1.先注释掉readImage() 2.注释掉readImage() try { writeImage(); //readImage(); } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
执行后, 测试结果打印“1”,那么就说明插入成功了。哎,总算用JDBC把图片存进去了。能否读出来,别急,把writeImage()注释掉。用readImage()方法,看看在D盘根目录能否生成图片文件。我试过后发现可以哈。。。松了一口气,待会再试试为什么用Hibernate就无法插入。
检查了下,表结构,不可能是使用了MySQL的保留字。
且当使用如下Hibernate测试代码的时候,可以通过:
import java.io.InputStream; import java.sql.Blob; import java.sql.SQLException; import org.hibernate.Hibernate; import org.hibernate.Session; import cn.com.servyou.bbs.domain.Image; import cn.com.servyou.bbs.util.FileUtil; import cn.com.servyou.bbs.util.HibernateSessionFactory; public class ImageDaoHibernateImplTest { public static void writeImage() { Image image = new Image(); byte[] bytes = FileUtil .getBytes("D:\\My Documents\\My Pictures\\20090731124506989.jpg"); // Blob blob = Hibernate.createBlob(bytes); Blob blob = Hibernate.createBlob(new byte[]{34,11,-2,55}); image.setBlob(blob); Session session = HibernateSessionFactory.getSession(); session.save(image); HibernateSessionFactory.closeSession(); } public static void readImage() throws SQLException { Session session = HibernateSessionFactory.getSession(); Image img = (Image) session.load(Image.class, new Integer(2)); Blob blob = img.getBlob(); InputStream inputStream = blob.getBinaryStream(); FileUtil.writeFile(inputStream, "d:\\b.jpg"); } public static void main(String[] args) { try { writeImage(); // readImage(); } catch (Exception e) { e.printStackTrace(); } } }
然而将换成 Blob blob = Hibernate.createBlob(bytes);
//Blob blob = Hibernate.createBlob(new byte[]{34,11,-2,55});
时报错了!
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: 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 '$T??ú2{??÷?#M`9;? ¤?2?tJp>1?÷D?<???Pm?òQ?mn?????Nè\'?.89??4…
这让我突然想起了,可能是MySQL字符集问题,将Hibnate配置文件中MySQL 的URL改成
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate_demo?useUnicode=true&characterEncoding=utf-8</property>
再执行下writeImage()方法,发现执行成功了,数据库表t_test里也有相应记录。
好,那再试试能不能读出来,并把这个二进制流,生成图片文件,放在D盘根目录。
将主函数中的writeImage注释掉。
//writeImage();
readImage();
执行后发现在D盘根目录便生成了图片文件,但是真正原理还没理解清楚,现在只是给出了处理方法。和大家分享下,望能和大家讨论下,到底是什么原因引起的,为什么JDBC操作BLOB没有字符集问题,而在使用Hibernate的API操作BLOB字段会出现问题。