转自:http://blog.csdn.net/lin_yongrui/article/details/#
oracle数据库当需要存入大数据量(大于4000)时,varchar2不够用,可以使用clob,本文描述clob怎么和Hibernate一起使用。
以公告Notice的公告内容noticeContent为例说明:
Notice表notice_content字段为clob类型;
Notice类的noticeContent属性为String;
Notice_hbm_xml映射文件为text类型:
LOB数据不能象其它类型数据一样直接插入(INSERT)。 插入前必须先插入一个空的LOB对象,CLOB类型的空对象为EMPTY_CLOB (),BLOB类型的空对象为EMPTY_BLOB()。
之后通过SELECT命令查询得到先前插入的记录并锁定,继而将空对象修改为所要插入的LOB对象。
StringBuffer sqlstr = new StringBuffer(); sqlstr.append("INSERT INTO notice t (t.notice_id,t.notice_type,t.notice_title," + "t.notice_status,t.sender,t.eff_date,t.exp_date,t.creater,t.create_time," + "t.notice_content) VALUES ("); sqlstr.append(+notice.getNoticeId() + ","); sqlstr.append("'" + notice.getNoticeType() + "',"); sqlstr.append("'" + notice.getNoticeTitle() + "',"); sqlstr.append("'" + notice.getNoticeStatus() + "',"); sqlstr.append("'" + notice.getSender() + "',"); sqlstr.append("sysdate,"); sqlstr.append("to_date('" + theForm.getEndDate2() + " 23:59:59','yyyy-MM-dd HH24:mi:ss'),"); sqlstr.append("'" + notice.getCreater() + "',"); sqlstr.append("sysdate,"); sqlstr.append("empty_clob()");//插入空值 sqlstr.append(")"); String sql = sqlstr.toString(); Class.forName(driverClassName); Connection con = DriverManager.getConnection(url, username, password); con.setAutoCommit(false);//设置不自动提交 PreparedStatement pstmt = con.prepareStatement(sql); String content = notice.getNoticeContent().replace('\'', '\"'); try { pstmt.execute(); con.commit();//插入 pstmt = con.prepareStatement("select notice_content from notice where notice_id="+notice.getNoticeId()+" for update");//查找刚刚插入的那条记录 for update ResultSet res = pstmt.executeQuery(); CLOB clob = null; while(res.next()){ clob = (oracle.sql.CLOB)res.getClob(1); clob.putString(1, content);//content为前台提交过来的公告内容,大数据量 } pstmt = con.prepareStatement("update notice set notice_content = ? where notice_id=?");//修改notice_content字段的内容 pstmt.setClob(1, clob); pstmt.setLong(2, notice.getNoticeId()); pstmt.executeUpdate(); con.commit(); if (nps != null && nps.size() > 0) { noticePartnerDao.saveOrUpdateAll(nps); } } catch (Exception e) { info.setCode("1"); info.setFlag(false); info.setInfo("发布公告失败!"); System.out.println(e.getMessage()); System.out.println(e.getStackTrace()); FileLog.errorLog(e, "发布公告失败"); return info; } finally { if(pstmt!=null) { pstmt.close(); } if(con!=null) { con.close(); } }
对于clob的修改,可在修改该表的其他字段信息时同时将clob字段修改为EMPTY_CLOB (),然后才对clob字段单独修改,方法与上相同。
存入clob类型的文字一般很多,页面不会直接使用textarea,可以使用开源的CKEditor文字编辑器代替,使用方法很简单很实用,详见:CKEditor的使用示例
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/203254.html原文链接:https://javaforall.net
