设为首页 收藏本站
查看: 1549|回复: 0

[经验分享] PostgreSQL + Hibernate 关于 Bytea 和 oid 的映射问题

[复制链接]

尚未签到

发表于 2016-11-20 12:28:08 | 显示全部楼层 |阅读模式
  问题起始,
  1. 我在pojo里面定义了一个 binaryData,想通过Blob类型映射,

public Blob getBinaryData() {
return _binaryData;
}
public void setBinaryData(Blob binaryData) {
this._binaryData = binaryData;
}
  2. Hibernate 配置文件片段

     <property name="_binaryData" access="field" type="blob" not-null="true">
<column name="BINARYDATA" not-null="true" />
</property>
  3. Database 对应的Column 为 bytea 
  4.Java 代码 

     InputStream stream = getClass().getResourceAsStream("CrissAngel.jpg");
picStorage1.setBinaryData(Hibernate.createBlob(stream));
_picStorageDAO.save( picStorage1 );
  4. 报错
  ERROR JDBCExceptionReporter - ERROR: column "binarydata" is of type bytea but expression is of type bigint
Hint: You will need to rewrite or cast the expression.
Position: 42
27 Jul 2010 17:12:13,828 ERROR AbstractFlushingEventListener - Could not synchronize database state with session

  问题追溯,
  1. PostgreSQL 用两种类型 bytea/oid 来 处理binary stream
  http://jdbc.postgresql.org/documentation/80/binary-data.html
  2. Hibernate BlobType 默认行为
转载自 http://blog.toadhead.net/index.php/2005/02/12/postgresql-blobs-with-hibernate/
  My test JDBC code looks something like:

PreparedStatement stmt = conn.prepareStatement("INSERT INTO foo (data) VALUES (?)");
stmt.setBlob(1, Hibernate.createBlob(myInputStream));
stmt.executeUpdate();
  The above example works fine. The Postgresql JDBC driver accepts any object that implements javax.sql.Blob.
  I therefore assumed that the following code would work:

HibernateObject o = new HibernateObject();
o.setBlob(Hibernate.createBlob(myInputStream));
hibernate.save(o);
  Unfortunately this doesn’t work. The problem lies in net.sf.hibernate.type.BlobType. Hibernate contains the following logic:

public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {

  
final boolean useInputStream = session.getFactory().getDialect().useInputStreamToInsertBlob()
    && BlobImplementer.class.isInstance( blob );
if (value instanceof BlobImpl) {
BlobImpl blob = (BlobImpl) value;
st.setBinaryStream( index, blob.getBinaryStream(), (int) blob.length() );
}
else {
st.setBlob(index, (Blob) value);
}
}
  The problem with the above code is that Postgresql uses setBinaryStream for byte array (bytea) fields. Hibernate incorrectly assumes that all databases can use setBinaryStream on blob fields.
  Steve Lustbader filed a bug HB-955 regarding this issue that has, unfortunately, been rejected. Fortunately, there is a fairly simple workaround. net.sf.hibernate.lob.BlobImpl is the Hibernate class that implements javax.sql.Blob. I copied the implementation of this class and put it in my own class. I then use this class to the set the blob field in my Hibernate object. Hibernate than passes this object onto the JDBC driver and everything works well.
  I understand the logic behind what is happening in Hibernate. They are trying to prevent problems with JDBC drivers that cast the blob field to their own implementation of javax.sql.Blob. I’m of the opinion that any JDBC driver that does this is broken. Any JDBC driver that does not accept any implementation of javax.sql.Blob is in my opinion broken. The assumption that all blobs can be set using setBinaryStream() is also incorrect, in my opinion.
  问题原因
  1. Postgres 保存 bytea 的 JDBC代码片段

For example, suppose you have a table containing the file names of images and you also want to store the image in a bytea  column:
CREATE TABLE images (imgname text, img bytea);
To insert an image, you would use:
File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO images VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setBinaryStream(2, fis, (int)file.length());
ps.executeUpdate();
ps.close();
fis.close();

  由此可见,bytea 必须执行 ps.setBinaryStream 方法.
  但是 Hibernate 默认的行为时执行   st.setBlob(index, (Blob) value); 因为 session.getFactory().getDialect().useInputStreamToInsertBlob() 永远都返回 FALSE.

解决办法

  方法1 - 改成 byte[] 类型  
  由于 bytea 直接支持 byte[] 可以用 ps.setBytes() 直接赋值.
    所以可以作如下修改

public byte[] getBinaryData() {
return _binaryData;
}
public void setBinaryData(byte[] binaryData) {
this._binaryData = binaryData;
}
  配置文件,  

        <property name="_binaryData" access="field" type="byte[]" not-null="true">
<column name="BINARYDATA" not-null="true" />
</property>
  测试代码,

  InputStream stream = getClass().getResourceAsStream("CrissAngel.jpg");
byte[] input = new byte[stream.available()];
stream.read(input);
picStorage1.setBinaryData(input);
_picStorageDAO.save( picStorage1 ); 
  
   这样做可以 通过Hibernate 保存和读取 bytea 类型,但是 必须将所有的 binary data 读入到内存,如果在并发环境下很容易导致 OutOfMemory 的问题. 还有可移植性太差,以后如果换成MySQL数据库,那么所有的Byte[] 对应的bytea Blob类型需要全部改回成BLOB,包括所有的实现方法.
  方法二,撰写自己的 PostgreSQLDialect

public class MyPostgreSQLDialect extends PostgreSQLDialect {
@Override
public boolean useInputStreamToInsertBlob() {
// TODO Auto-generated method stub
return true;
}
}
  目的是让 BlobType 执行 ps.setBinaryStream(... 方法来保存Blob类型.  (注,如果要用 oid 类型,此法不可取)
  配置文件

<prop key="hibernate.dialect">
com.haodao.dialect.MyPostgreSQLDialect
</prop>
  这样,无需改动原有配置,程序正常执行,也保留了 stream 的特性,易于移植同事也不会带来高并发下OutOfMemory的问题
  

 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-302942-1-1.html 上篇帖子: (转载)PostgreSQL 利用Pgpool-II的集群搭建方案 下篇帖子: Trac + Subversion + Mod_Python + Apache2 + PostgreSQL for RH
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表