Hibernate Blob數(shù)據(jù)類型映射的一個例子
以下為Hibernate Blob數(shù)據(jù)類型映射的一個例子,通過例子來把握Hibernate Blob數(shù)據(jù)類型映射。
Hibernate Blob:Java 代碼:
- public class User implements
- Java.io.Serializable {
- // Fields
- private long id;
- private String name;
- private String email;
- private String addr;
- //定義Blob的pthto
- private Blob photo;
Hibernate Blob:xml 代碼:
- <Hibernate-mapping>
- <class name="org.tie.User" table="user" catalog="tie">
- <id name="id" type="long">
- <column name="id" />
- <generator class="identity" />
- </id>
- <property name="name" type="string">
- <column name="name" length="45" not-null="true" />
- </property>
- <property name="email" type="string">
- <column name="email" length="45" />
- </property>
- <property name="addr" type="string">
- <column name="addr" length="45" />
- </property>
- <!-- 映射blob類型 -->
- <property name="photo" type="blob">
- <column name="photo" />
- </property>
- </class>
- </Hibernate-mapping>
兩個測試方法:
Java 代碼:
- public void testCreate(){
- User user = new User();
- user.setName("linweiyang");
- user.setAddr("beijing");
- user.setEmail("linweiyang@163.com");
- Blob photo = null;
- try {
- //將圖片讀進輸入流
- FileInputStream fis = new FileInputStream("c:\\a.jpg");
- //轉(zhuǎn)成Blob類型
- photo = Hibernate.createBlob(fis);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- user.setPhoto(photo);
- Session session = factory.openSession();
- Transaction tr = session.beginTransaction();
- session.save(user);
- tr.commit();
- session.close();
- }
- public void testRerieve(){
- Session session = factory.openSession();
- User user = (User)session.load(User.class, new Long(3));
- try {
- //從數(shù)據(jù)庫中要讀取出來
- InputStream is = user.getPhoto().getBinaryStream();
- //在把寫到一個圖片格式的文件里
- FileOutputStream fos = new FileOutputStream("c:\\linweihan.jpg");
- byte[] buffer = new byte[1024];
- int len = 0;
- //從數(shù)據(jù)庫中讀取到指定的字節(jié)數(shù)組中
- while((len = is.read(buffer) )!= -1){
- //從指定的數(shù)組中讀取,然后輸出來,
- 所以這里buffer好象是連接inputStream和outputStream的一個東西
- fos.write(buffer,0,len);
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (IOException e){
- e.printStackTrace();
- }
- session.close();
- }
這么理解輸入輸出流,讀入流自然要有讀入的源頭,輸出也要輸出到某個地方,輸出一般是先要輸讀入,這里連接輸入和輸出的是一個在內(nèi)存中的字節(jié)數(shù)組buffer.這樣從數(shù)據(jù)庫中讀到這個數(shù)組里,輸出流在從這個數(shù)組中輸出到特定的文件格式里。以上便是Hibernate Blob數(shù)據(jù)類型映射的一個例子。
【編輯推薦】