日期:2014-05-16  浏览次数:20756 次

spring+hibernate,数据库插入图片

主要就三個地方需要配置:

<一>hbm中,

<property name="photo1" type="binary">
    <column name="photo1" not-null="false" />
</property>

<二>javabean中,

private byte[] photo1 ;
public void setPhoto1(byte[] photo1) {
	this.photo1 = photo1;
}

public byte[] getPhoto1() {
	return photo1;
}

?<三>spring的applicationContext.xml中,

<!--声明一个处理句柄 Blob-->
  	<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" lazy-init="true" />
?

這樣再加上把File转成byte[]的方法,就ok了

//傳入的File 轉成byte[]
	public byte[] inputToByte( File f ){
		try {
			FileInputStream fis = new FileInputStream( f );
			byte[] buffer = new byte[1024];  
			int read;  
			ByteArrayOutputStream byteArray = new ByteArrayOutputStream();  
			while((read = fis.read(buffer))>0)  
			{  
				byteArray.write(buffer,0,read);  
				byteArray.flush();  
			}  
			byte[]   bt   =   byteArray.toByteArray();
			byteArray.close();
			return bt ;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
?

.