最近,使用Hibernate操作Clob。上網看了不少資料,感覺五花八門,實作起來的方法都各不相同。
有的是Hibernate2.0上的。有的是加入了spring的支援,把clob當成string做處理(的确很好,但是不适合新手)
........
而且,某些代碼根本都執行不了~浪費我們的時間,55555555。
于是,法老參考了一些官網的方法加以修改,幹脆重新寫一個完整元操作版本。
包含:insert,update,delete,select 四大基本方法!
供大家參考!
-------------------------------------------
測試環境介紹:
WINDWOS XP SP2;Eclipse 3.2;JDK 1.4.2
Hibernate-Version: 3.0.5 ; oracle 9i ;
=====================
重點說明:
1。配置檔案hbm.xml裡把clob的type="clob"
片段如下
<property name="bsznContent" type="clob">
<column name="BSZN_CONTENT" not-null="true" />
</property>
2。實體bean中,導入java.sql.Clob包 (注意不是oracle.sql.CLOB 個人習慣用血統純點的.這裡鄙視一下oracle。嘿嘿)
在該字段對應的實體檔案裡面,增加以下兩個變量及其相應的get/set方法
import java.sql.Clob;
...
private Clob bsznContent;
private String bsznContentString;
...
public Clob getBsznContent() {
return this.bsznContent;
}
public void setBsznContent(Clob bsznContent) {
this.bsznContent = bsznContent;
}
public String getBsznContentString() {
return bsznContentString;
}
public void setBsznContentString(String bsznContentString) {
this.bsznContentString = bsznContentString;
}
bsznContent 屬性是預設的clob,bsznContentString 屬性是對bsznContent做轉換時候用的
----------------------------------------
好了廢話不多說,把代碼寫下來吧~
建表SQL
=================
create table "cmp_bszn" ( "id" INTEGER not null, "kind" CHAR(2) not null, "bszn_title1" VARCHAR2(200) not null, "bszn_title2" VARCHAR2(200), "bszn_code" VARCHAR2(50), "bszn_bumen" VARCHAR2(50), "bszn_date" VARCHAR2(50), "bszn_content" CLOB not null, "sys_date" DATE default SYSDATE not null, constraint PK_CMP_BSZN primary key ("id") );
hibernate.cfg.xml 由于調試用,用的是JDBC連接配接方法,要使用連接配接池,請自行修改.
記得自己把資料庫位址和使用者名,秘密改下
<?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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.username">sa</property> <property name="connection.url"> jdbc:oracle:thin:@127.0.0.1:1521:web </property> <property name="dialect"> org.hibernate.dialect.Oracle9Dialect </property> <property name="connection.password">saweb</property> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property> <property name="show_sql">true</property> <property name="connection.useUnicode">true</property> <property name="connection.characterEncoding">GBK</property> <!-- 設定事務管理的工廠類 --> <property name="hibernate.transaction.factory_class"> org.hibernate.transaction.JDBCTransactionFactory </property> <property name="hibernate.query.factory_class"> org.hibernate.hql.classic.ClassicQueryTranslatorFactory </property> <mapping resource="clob/cmpBszn.hbm.xml" /> </session-factory> </hibernate-configuration>
cmpBszn.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse - Hibernate Tools --> <hibernate-mapping> <class name="cmpBszn" table="CMP_BSZN" schema="SA"> <id name="id" type="java.lang.Long"> <column name="ID" precision="22" scale="0" /> <generator class="increment"></generator> </id> <property name="kind" type="java.lang.String"> <column name="KIND" length="2" not-null="true" /> </property> <property name="bsznTitle1" type="java.lang.String"> <column name="BSZN_TITLE1" length="200" not-null="true" /> </property> <property name="bsznTitle2" type="java.lang.String"> <column name="BSZN_TITLE2" length="200" /> </property> <property name="bsznCode" type="java.lang.String"> <column name="BSZN_CODE" length="50" /> </property> <property name="bsznBumen" type="java.lang.String"> <column name="BSZN_BUMEN" length="50" /> </property> <property name="bsznDate" type="java.lang.String"> <column name="BSZN_DATE" length="50" /> </property> <property name="bsznContent" type="clob"> <column name="BSZN_CONTENT" not-null="true" /> </property> <property name="sysDate" type="java.util.Date"> <column name="SYS_DATE" length="7" not-null="true" /> </property> </class> </hibernate-mapping>
抽象類AbstractcmpBszn.java
// default package import java.sql.Clob; import java.util.Date; public abstract class AbstractcmpBszn implements java.io.Serializable ...{ // Fields private Long id; private String kind; private String bsznTitle1; private String bsznTitle2; private String bsznCode; private String bsznBumen; private String bsznDate; private Clob bsznContent; private String bsznContentString; private Date sysDate; // Constructors public AbstractcmpBszn() ...{ } public AbstractcmpBszn(String kind, String bsznTitle1, Clob bsznContent, Date sysDate) ...{ this.kind = kind; this.bsznTitle1 = bsznTitle1; this.bsznContent = bsznContent; this.sysDate = sysDate; } public AbstractcmpBszn(String kind, String bsznTitle1, String bsznTitle2, String bsznCode, String bsznBumen, String bsznDate, Clob bsznContent, Date sysDate) ...{ this.kind = kind; this.bsznTitle1 = bsznTitle1; this.bsznTitle2 = bsznTitle2; this.bsznCode = bsznCode; this.bsznBumen = bsznBumen; this.bsznDate = bsznDate; this.bsznContent = bsznContent; this.sysDate = sysDate; } // Property accessors public Long getId() ...{ return this.id; } public void setId(Long id) ...{ this.id = id; } public String getKind() ...{ return this.kind; } public void setKind(String kind) ...{ this.kind = kind; } public String getBsznTitle1() ...{ return this.bsznTitle1; } public void setBsznTitle1(String bsznTitle1) ...{ this.bsznTitle1 = bsznTitle1; } public String getBsznTitle2() ...{ return this.bsznTitle2; } public void setBsznTitle2(String bsznTitle2) ...{ this.bsznTitle2 = bsznTitle2; } public String getBsznCode() ...{ return this.bsznCode; } public void setBsznCode(String bsznCode) ...{ this.bsznCode = bsznCode; } public String getBsznBumen() ...{ return this.bsznBumen; } public void setBsznBumen(String bsznBumen) ...{ this.bsznBumen = bsznBumen; } public String getBsznDate() ...{ return this.bsznDate; } public void setBsznDate(String bsznDate) ...{ this.bsznDate = bsznDate; } public Clob getBsznContent() ...{ return this.bsznContent; } public void setBsznContent(Clob bsznContent) ...{ this.bsznContent = bsznContent; } public Date getSysDate() ...{ return this.sysDate; } public void setSysDate(Date sysDate) ...{ this.sysDate = sysDate; } public String getBsznContentString() ...{ return bsznContentString; } public void setBsznContentString(String bsznContentString) ...{ this.bsznContentString = bsznContentString; } }
實體類cmpBszn
// default package // Generated by MyEclipse - Hibernate Tools import java.sql.Clob; import java.util.Date; public class cmpBszn extends AbstractcmpBszn implements java.io.Serializable ...{ // Constructors public cmpBszn() ...{ } public cmpBszn(String kind, String bsznTitle1, Clob bsznContent, Date sysDate) ...{ super(kind, bsznTitle1, bsznContent, sysDate); } public cmpBszn(String kind, String bsznTitle1, String bsznTitle2, String bsznCode, String bsznBumen, String bsznDate, Clob bsznContent, Date sysDate) ...{ super(kind, bsznTitle1, bsznTitle2, bsznCode, bsznBumen, bsznDate, bsznContent, sysDate); } }
SessionManager管理類(這個是通用的,如果你要自己寫也可以)
package Hib_DB; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public class SessionManager ...{ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal threadLocal = new ThreadLocal(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; private SessionManager() ...{ } public static Session getSession() throws HibernateException ...{ Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) ...{ if (sessionFactory == null) ...{ rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } public static void rebuildSessionFactory() ...{ try ...{ configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) ...{ System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } public static void closeSession() throws HibernateException ...{ Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) ...{ session.close(); } } public static org.hibernate.SessionFactory getSessionFactory() ...{ return sessionFactory; } public static void setConfigFile(String configFile) ...{ SessionManager.configFile = configFile; sessionFactory = null; } public static Configuration getConfiguration() ...{ return configuration; } }
Test_Work實際測試類
import java.sql.SQLException; import java.util.Date; import java.util.Iterator; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import Hib_DB.SessionManager; public class Test_Work ...{ public static void main(String[] args) throws SQLException ...{ Test_Work exam = new Test_Work(); exam.InsertRecords(); exam.QueryRecords(); exam.Demo_Update(new Long(5)); exam.DeleteRecords(new Long(3)); } private void QueryRecords() throws SQLException ...{ try ...{ Session session = SessionManager.getSession(); Query records = session.createQuery("from cmpBszn order by id"); List record = records.list(); Iterator iterator = record.iterator(); while (iterator.hasNext()) ...{ cmpBszn obj = (cmpBszn) iterator.next(); System.out.println(obj.getId() + "" + obj.getKind()); java.sql.Clob clob = obj.getBsznContent(); if (clob != null) ...{ String b1 = clob.getSubString(1, (int) clob.length()); obj.setBsznContentString(b1); } System.out.println(obj.getBsznContentString()); System.out.println("----------------------------------"); } System.out.println(record.size()); } catch (HibernateException e) ...{ System.out.println("error"); } finally ...{ try ...{ // Step 5 - close the session SessionManager.closeSession(); } catch (HibernateException e1) ...{ // do nothing } } } private void QueryRecords(Long id) throws SQLException ...{ try ...{ Session session = SessionManager.getSession(); Query records = session .createQuery("from cmpBszn order by id where id = " + id); List record = records.list(); Iterator iterator = record.iterator(); while (iterator.hasNext()) ...{ cmpBszn obj = (cmpBszn) iterator.next(); java.sql.Clob clob = obj.getBsznContent(); if (clob != null) ...{ String b1 = clob.getSubString(1, (int) clob.length()); obj.setBsznContentString(b1); } System.out.println(obj.getId() + "" + obj.getKind() + "" + obj.getBsznTitle1()); System.out.println("内容:" + obj.getBsznContentString()); System.out.println("----------------------------------"); } } catch (HibernateException e) ...{ System.out.println("error"); } finally ...{ try ...{ // Step 5 - close the session SessionManager.closeSession(); } catch (HibernateException e1) ...{ // do nothing } } } private void InsertRecords() ...{ String kind = "03"; String bsznTitle1 = "ttttttttt"; String bsznContentString = "哈哈成功了"; Date sysDate = new Date(); try ...{ Session session = SessionManager.getSession(); Transaction tx = session.beginTransaction(); cmpBszn obj = new cmpBszn(); obj.setKind(kind); obj.setBsznTitle1(bsznTitle1); obj.setSysDate(sysDate); obj.setBsznContent(Hibernate.createClob(bsznContentString));//關鍵createClob方法 session.save(obj); tx.commit(); System.out.println("Save Success."); } catch (Exception e) ...{ System.out.println("Save failed."); } finally ...{ try ...{ SessionManager.closeSession(); } catch (HibernateException e1) ...{ } } } //修改 private void UpdateRecords(Long id) ...{ String kind = "03"; String bsznTitle1 = "update_test"; String bsznContentString = "修改更新"; Date sysDate = new Date(); try ...{ Session session = SessionManager.getSession(); Transaction tx = session.beginTransaction(); cmpBszn obj = (cmpBszn) session.load(cmpBszn.class, id); obj.setKind(kind); obj.setBsznTitle1(bsznTitle1); obj.setSysDate(sysDate); obj.setBsznContent(Hibernate.createClob(bsznContentString));// 關鍵 session.update(obj); tx.commit(); System.out.println("Save Success."); } catch (Exception e) ...{ System.out.println("Save failed."); } finally ...{ try ...{ SessionManager.closeSession(); } catch (HibernateException e1) ...{ } } } private void DeleteRecords(Long id) ...{ try ...{ Session session = SessionManager.getSession(); cmpBszn message = (cmpBszn) session.load(cmpBszn.class, id); Transaction tx = session.beginTransaction(); session.delete(message); tx.commit(); System.out.println("Delete successful."); } catch (HibernateException e) ...{ // TODO 自動生成 catch 塊 e.printStackTrace(); System.out.println("删除失敗!"); } finally ...{ try ...{ // Step 5 - close the session SessionManager.closeSession(); } catch (HibernateException e1) ...{ // do nothing } } } private void Demo_Update(Long id) throws SQLException ...{ System.out.println("修改前:"); this.QueryRecords(id); this.UpdateRecords(id); System.out.println("修改後:"); this.QueryRecords(id); } }
--------------------------------------------
好了~基本的核心代碼都在這裡了~
寫完後才發現QueryRecords(Long id)這個方法寫的比較呆~效率不高~大家可以自己改寫~
參考文章:
關于Clob類型在Hibernate中的應用小結 找不到原始位址了
Mapping a Clob to a Stringhttp://www.hibernate.org/76.html
Using Clobs with Oracle and Hibernate 1.2