最近在“玩”hibernate Annotation,弄了個Attachment保存進(jìn)數(shù)據(jù)庫的測試,附件內(nèi)容保存在content屬性里面。
??@Lob
??@Column(columnDefinition?=?"LongBlob")
??public?byte[]?getContent()?{
????return?content;
??}
一開始,配置mysql jdbc url如下
jdbc.url????????????=????jdbc:mysql://localhost/test\
?????????????????????????????useUnicode=true\
????????????????????????????&characterEncoding=gbk
一測試,報錯
Caused?by:?java.sql.BatchUpdateException:?Syntax?error?or?access?violation?message?from?server:?"You?have?an?error?in?your?SQL?syntax?near?''D0CF11E0A1B11AE1000000000000000000000000000000003E000300FEFF0900060000000000000'?at?line?1"
????at?com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1540)
同樣的語句,直接在mysql命令行下運行就沒問題,偏偏jdbc上就有這臭毛病。換jdbc driver版本,改@Lob為 @Type(type = "org.springframework.orm.hibernate3.support.BlobByteArrayType"),改hibernate配置(比如hibernate.jdbc.use_streams_for_binary true),甚至是直接用jdbc來insert,亂七八糟折騰半天,問題照舊。最后只好用上“歪”招,把byte[]配成String,在保存的時候把byte[]保存成hex String格式,取的時候再解碼回來。
歪招終歸是歪招,這兩天老為這東西心煩,晚上吃飯的時候無意中想起charset的問題,把代碼撿回來再測試了一下,問題解決,哈哈!
jdbc.url????????????=????jdbc:mysql://localhost/mmwy_blog\
?????????????????????????????useUnicode=true\
????????????????????????????&characterEncoding=utf-8
如果設(shè)成iso-8859-1、utf-8,保存一點問題都沒有,換用gbk、gb2312、big5之類的字符集,問題就出來了。