Hibernate操作Clob类型完整版! (转)
最近,使用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
/**//* Table: "cmp_bszn" 相关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; /** *//** * AbstractcmpBszn generated by MyEclipse - Hibernate Tools */ 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 /** *//** default constructor */ public AbstractcmpBszn() ...{ } /** *//** minimal constructor */ public AbstractcmpBszn(String kind, String bsznTitle1, Clob bsznContent, Date sysDate) ...{ this.kind = kind; this.bsznTitle1 = bsznTitle1; this.bsznContent = bsznContent; this.sysDate = sysDate; } /** *//** full constructor */ 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; /** *//** * cmpBszn generated by MyEclipse - Hibernate Tools */ public class cmpBszn extends AbstractcmpBszn implements java.io.Serializable ...{ // Constructors /** *//** default constructor */ public cmpBszn() ...{ } /** *//** minimal constructor */ public cmpBszn(String kind, String bsznTitle1, Clob bsznContent, Date sysDate) ...{ super(kind, bsznTitle1, bsznContent, sysDate); } /** *//** full constructor */ 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; /** *//** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class SessionManager ...{ /** *//** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ 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() ...{ } /** *//** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ 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; } /** *//** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() ...{ try ...{ configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) ...{ System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** *//** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException ...{ Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) ...{ session.close(); } } /** *//** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() ...{ return sessionFactory; } /** *//** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) ...{ SessionManager.configFile = configFile; sessionFactory = null; } /** *//** * return hibernate configuration * */ 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 ...{ /** *//** * @param args * @throws SQLException * @throws SQLException * /*==============================================================*/ /**//* Table: "cmp_bszn" 相关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") ); */ public static void main(String[] args) throws SQLException ...{ Test_Work exam = new Test_Work(); /**//*Insert*/ exam.InsertRecords(); exam.QueryRecords(); /**//*Update*/ exam.Demo_Update(new Long(5)); /**//*Delete*/ 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)这个方法写的比较呆~效率不高~大家可以自己改写~