java hibernate 對映和註解oracle含有blob欄位的資料表的pojo原始碼
阿新 • • 發佈:2019-02-08
將oracle資料表blob欄位對映到hibernate pojo的byte[]屬性,構造pojo時,直接傳入byte陣列即可,如果需要傳入一個File物件,只需使用FileUtils.readFileToByteArray(file)將File轉換為byte[]型位元組流陣列即可, 閒話不說,直接貼原始碼:
package db.hbm; import java.sql.Blob; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; import org.springframework.orm.hibernate3.support.BlobByteArrayType; /** * Files entity. @author MyEclipse Persistence Tools */ @TypeDefs({@TypeDef(name="pic",typeClass=BlobByteArrayType.class)}) @Entity @Table(name = "FILE") public class File implements java.io.Serializable { // Fields private String id; private String filename; private byte[] data; //使用byte[]陣列對映blob欄位 // Constructors /** default constructor */ public File() { } /** full constructor */ public File(String filename,byte[] data) { this.filename = filename; this.data = data; } // Property accessors @GenericGenerator(name = "generator", strategy = "uuid") @Id @GeneratedValue(generator = "generator") @Column(name = "ID", unique = true, nullable = false, length = 50) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Column(name = "FILENAME", nullable = false, length = 200) public String getFilename() { return this.filename; } public void setFilename(String filename) { this.filename = filename; } @Lob @Basic(fetch=FetchType.LAZY) @Type(type = "org.springframework.orm.hibernate3.support.BlobByteArrayType") @Column(columnDefinition = "BLOB", name = "DATA", nullable = false) //@Type(type="pic") //@Column(name = "DATA", nullable = false) public byte[] getData() { return this.data; } public void setData(byte[] data) { this.data = data; } }