Spring+Hibernate处理Oracle lob字段(二)

Spring+Hibernate处理Oracle lob字段(一) 中说明了使用spring+hibernate处理lob字段的方式,这里在说明一下使用另一种方式处理lob字段(以clob为例)。

首先,将Pojo里面的属性定义为clob类型:

protected Clob contentClob;

hibernate.hbm.xml配置如下:

<property name="contentClob" column="contents" 
			type="java.sql.Clob"/>
 

Dao使用的方法如下:

public <T> void update(final T entity) throws Exception {
		getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						entity.setContentClob(Hibernate.createClob(" "));
						session.update(entity);
						session.flush();
						session.refresh(entity, LockMode.UPGRADE);
						SerializableClob serializableClob = 
    (SerializableClob)entity.getContentClob();
						Clob clob = serializableClob.getWrappedClob();
						if (clob instanceof oracle.sql.CLOB) {
                                               //此处要转化成Oracle.sql.CLOB类型
							java.io.Writer writer = 
    ((oracle.sql.CLOB)clob).getCharacterOutputStream();
							try {
								if (entity.getContents() != null 
    && !"".equals(entity.getContents())) {
									writer.write(entity.getContents());
									writer.flush();
								}
							} catch (IOException e) {
								e.printStackTrace();
								throw new RuntimeException();
							} finally {
								try {
									writer.close();
									writer = null;
								} catch (IOException e) {
								}
							}
						}
						session.flush();
						//session.connection().commit();
						return null;
					}	
				}
			);
	}

 使用以上的方式也能正确的插入和更新Clob字段而不用升级JDBC驱动。由于这里要采用两步操作(先插入,再更新)实现,所以要加上事务管理,使用spring的声明式事务即可。

注意:

1.Pojo中要加个字符串类型的属性,如:

protected String contents;

 用于存放将要保存到CLOB中的内容。

2.POJO中增加一个方法,用户转换Clob的内容为String

public String getContentClobToString() {
        if (this.contentClob != null && !"".equals(this.contentClob.toString().trim())) {
            try {
                return this.contentClob.getSubString(1L, (int)this.contentClob.length());
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return "";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值