大字段(CLOB 存長文本、BLOB 存二進制)雖方便,但過大數據會嚴重拖垮查詢效能、佔用記憶體、增加連接負載。本文演示在達夢數據庫中,使用 Hibernate 正確映射與持久化大字段的完整流程。
CREATE TABLE TESTLOB (
ID INT PRIMARY KEY,
TITLE VARCHAR(50),
CLOBNAME VARCHAR(50),
CLOBCONTENT CLOB,
BLOBNAME VARCHAR(50),
BLOBCONTENT BLOB
);
CREATE SEQUENCE "TESTLOB"."SEQ_TESTLOB_ID"
INCREMENT BY 1 START WITH 1 MAXVALUE 100000 MINVALUE 1 NOCYCLE;
public class TestLob {
private int id;
private String title, clobName, clobContent, blobName;
private byte[] blobContent;
// getter/setter 省略
}
<hibernate-mapping>
<class name="com.dm.lobtest.vo.TestLob" table="TESTLOB">
<id name="id" column="ID" type="int">
<generator class="sequence">
<param name="sequence">SEQ_TESTLOB_ID</param>
</generator>
</id>
<property name="title" column="TITLE" type="string"/>
<property name="clobName" column="CLOBNAME" type="string"/>
<property name="blobName" column="BLOBNAME" type="string"/>
<property name="clobContent" column="CLOBCONTENT" type="string"/> <!-- CLOB → String -->
<property name="blobContent" column="BLOBCONTENT" type="binary"/> <!-- BLOB → byte[] -->
</class>
</hibernate-mapping>
關鍵點:CLOB 映射 type="string",BLOB 映射 type="binary",主鍵使用 sequence 生成器關聯達夢 Sequence。
<form name="myTestLobFrm" method="post" enctype="multipart/form-data"
action="/LobTest/testlob.do?method=save">
<input type="text" name="title" />
<textarea name="clobTest" rows="20" cols="80"></textarea>
<input type="file" name="blobTest" />
<input type="submit" value="確認"/>
</form>
public class TestLobAction extends DispatchAction {
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest req, HttpServletResponse res) throws Exception {
TestLob testLob = new TestLob();
testLob.setTitle(req.getParameter("title"));
// BLOB:Struts FormFile 獲取上傳文件
FormFile blobFile = (FormFile) form.getMultipartRequestHandler().getFileElements().get("blobTest");
testLob.setBlobName(blobFile.getFileName());
testLob.setBlobContent(blobFile.getFileData()); // byte[]
// CLOB:直接獲取文本域內容
testLob.setClobName(testLob.getTitle());
testLob.setClobContent(req.getParameter("clobTest"));
TestLobService.getInstance().createTestLob(testLob);
return mapping.findForward("success");
}
}
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static final ThreadLocal threadSession = new ThreadLocal<>();
public static Session currentSession() throws HibernateException {
if (sessionFactory == null) buildSessionFactory();
Session s = threadSession.get();
if (s == null) { s = sessionFactory.openSession(); threadSession.set(s); }
return s;
}
public static void closeSession() { ... }
}
public int createTestLob(TestLob testLob) {
Session session = null;
try {
session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
session.save(testLob);
tx.commit();
return 1;
} catch (Exception e) { e.printStackTrace(); return 0; }
finally { HibernateUtil.closeSession(); }
}
掌握類型映射與 Session 管理,即可在達夢上穩健處理 CLOB/BLOB 業務。