關於BLOB、CLOB,可以先參考一下 將 檔案存入資料庫 這篇文章。
在Hibernate中,您可以直接對Blob、Clob作映射,例如在T_USER表格中,若有BLOB與CLOB欄位分別為photo與resume,則您可以如下設計一個User類別:
- User.java
package onlyfun.caterpillar;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
@Table(name="T_USER")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private Long age;
@Lob
private byte[] photo;
@Lob
private char[] resume;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Long getAge() { return age; }
public void setAge(Long age) { this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public byte[] getPhoto() { return photo; }
public void setPhoto(byte[] photo) { this.photo = photo; }
public char[] getResume() { return resume; }
public void setResume(char[] resume) { this.resume = resume; }
}
無論是映射至BLOB或CLOB的欄位,在JPA中都是使用@Lob來標註,而JPA會自動根據屬性來判斷是要採用BLOB或CLOB的處理方式儲存至表格中,若屬性是byte[]型態,則以BLOB方式處理,若屬性是char[]型態,則使用CLOB方式處理。
一個儲存檔案至表格的範例如下:
FileInputStream inputStream =
new FileInputStream("c://workspace//caterpillar.jpg");
byte[] photo = new byte[inputStream.available()];
inputStream.read(photo);
inputStream.close();
User user = new User();
user.setName("caterpillar");
user.setAge(new Long(35));
user.setPhoto(photo);
user.setResume("Bla....Bla....resume text!!".toCharArray());
EntityManager entityManager =
JPAUtil.getEntityManagerFactory().createEntityManager();
EntityTransaction etx = entityManager.getTransaction();
etx.begin();
entityManager.persist(user);
etx.commit();
entityManager.close();
而一個取出檔案的範例如下:
EntityManager entityManager =
JPAUtil.getEntityManagerFactory().createEntityManager();
EntityTransaction etx = entityManager.getTransaction();
etx.begin();
User user = entityManager.find(User.class, id);
etx.commit();
entityManager.close();
FileOutputStream outputStream =
new FileOutputStream("c://workspace//caterpillar2.jpg");
outputStream.write(user.getPhoto());
outputStream.close();