Hibernate 存储SQL Server image 类型的文件
有以下注意点:
1.MyEclipse反向工程后得到image的对应的类型竟然是String,要把它改成byte[]
private byte[] fileData;
public byte[] getFileData() { return this.fileData; }
public void setFileData(byte[] fileData) { this.fileData = fileData; }
2.在XX.hbm.xml配置文件中,相应字段改为binary
<?xml version="1.0"encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd "> <!-- Mapping fileautogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="dao.Data" table="data" schema="dbo"catalog="Test"> <id name="id"type="java.lang.Integer"> <column name="id" /> <generator class="native" /> </id> <property name="startTime"type="java.util.Date"> <column name="startTime" length="23"/> </property> <property name="endTime"type="java.util.Date"> <column name="endTime" length="23"/> </property> <property name="fileData"type="binary"> <column name="fileData" /> </property> </class> </hibernate-mapping>
3.上传及下载测试代码如下:
package test;
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date;
import org.hibernate.Session; import org.hibernate.Transaction;
import dao.Data; import dao.DataDAO;
public class Test {
public static void main(String[] args) throwsIOException {
Session session = newDataDAO().getSession(); Transaction tx =session.beginTransaction();
// 存入文件 Data data = new Data(); data.setStartTime(newDate()); data.setEndTime(newDate());
InputStream in = null; in = newFileInputStream("d:/sample.jpg"); byte[] b = newbyte[in.available()]; in.read(b); in.close();
data.setFileData(b); session.save(data);
// 取出文件 Data data2 = (Data)session.load(Data.class, new Integer(1)); OutputStream out = null; out = newFileOutputStream("f:/sample.jpg"); out.write(data2.getFileData()); out.flush(); out.close();
tx.commit(); session.close();
}
}