在數(shù)據(jù)表對(duì)應(yīng)的實(shí)體內(nèi)中長文本與二進(jìn)制文件對(duì)應(yīng)的屬性為:
- 長文本對(duì)應(yīng)String類型
- 二進(jìn)制文件對(duì)應(yīng) Blob類型(java.sql.Blob)
//長文本
private String context;
//二進(jìn)制
private Blob img;
在配置文件中 通過property標(biāo)簽的 type屬性設(shè)置:
- 二進(jìn)制文件 type="blob"
- 長文本 "clob"
- 兩者可以通過property標(biāo)簽sql-type屬性進(jìn)行精確指定
<!--二進(jìn)制 -->
<property name="img" type="blob"></property>
<!-- 長文本 -->
<!-- <property name="context" type="clob"></property> -->
<!-- 長文本 精確指定 -->
<property name="context">
<column name="CONTEXT" sql-type="mediumtext"></column>
</property>
代碼中使用:
長文本和普通文本方式一樣
- 二進(jìn)制文件存放數(shù)據(jù)庫
主要解決Blob對(duì)象如何得來可以使用Hibernate提供的工具
/**
* test二進(jìn)制保存
*/
public static void testSaveBlob() {
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();// 配置文件configure()
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
News news = new News("上海", "好久沒有下雨", new Date(new Date().getTime()));
news.setContext("我的長文本");
// 二進(jìn)制保存
try {
//文件輸入流
InputStream stream = new FileInputStream("xxxxx.png");
Blob img = Hibernate.getLobCreator(session).createBlob(stream, stream.available());
news.setImg(img);
} catch (Exception e) {
e.printStackTrace();
}
//保存
session.save(news);
transaction.commit();
session.close();
sessionFactory.close();
}
- 二進(jìn)制文件從數(shù)據(jù)庫中讀取
通過獲取數(shù)據(jù)庫Blob對(duì)象獲取流
/**
* test二進(jìn)制讀取
*/
public static void testGetBlob() {
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();// 配置文件configure()
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
//獲取記錄
News news = session.get(News.class, 2);
//獲取記錄中二進(jìn)制
Blob img = news.getImg();
try {
//獲取對(duì)應(yīng)流
InputStream in = img.getBinaryStream();
System.out.println(in.available());
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 獲取流
transaction.commit();
session.close();
sessionFactory.close();
}