hibernate对象类型
对象类型的映射
保存图片到数据库
//写入blob数据对象
public void testWriteBlob(){
//new 一个学生对象
Student student=new Student(1,"张三封","男",new Date(),"武当山");
//得到文件
File file=new File("d:"+File.separator+"文件名");
//获取照片文件的输入流
InputStream inputStream=new FileInputStream(f);
//创建一个blob对象
Blob image=hibernate.getLobCreator(session).createBlob(input,input.availbale);
//设置照片属性
student.setPicture(image);
//保存学生
session.save(s);
session.submit();
}
public void testReadBlob(){
//获取学生对象
Student s= (Student)Session.get(Student.class,1);
//获取Blob对象
Blob image=s.getPicture();
//获取照片的输入流
InputStream inputstream=image.getBinaryStream();
//创建输出流
File f=new File("d:"+File.separator+"dest.jpg');
OutputStream outputStream=new FileOutputStream(f);
//创建缓冲区
byte[] byte=new byte[input.available()];
input.read(buff);
output.write(buff);
input.close();
output.close();
}
文件分隔符 File.separator
File f=new File("d"+File.separator+"文件名");
//创建一个Blob对象
Blob imgage=Hibernate.getLobCreator(session).createBlob(input,input.availabe())
hibernate与java对象类型的关系映射
取出数据库中的二进制数据输出为文件
session.get()方法获取数据库中的对象,需要进行类型强转
getBinaryStream():将Blob类型转换为InputStream
保存图片二进制数据的代码
Hibernate创建Blob类型的数据的方法:
Hibernate.getLobCreator(session).createBlob(input,input.available())

读取照片。
存入照片到数据库
有些版本的Hibernate可能不支持Hibernate.getLobCreator(session).createBlob(input,input.available());
可写成Hibernate.createBlob(input,input.available());
写blob类型的图片到数据库时,对象映射文件中的主键类型要改成assigned,native会报错
jdbc驱动包的版本不能过低,至少是5.1以上的
对象的类型
如何用hibernate写入对象类型的数据
clob和text对应大文本文件,blob对应大的二进制文件,例如视频音频图片 2.java中的clob对应存储大文本文件,java中的blob对应存储大二进制文件 MySQL不支持标准SQL的CLOB类型,在Mysql中,用TEXT,MEDIUMTEXT及LONGTEXT类型来表示长度超过255的长文本数据
@Test
public void saveImage() throws Exception{
Student s=new Student(1,"李四","男",new Date(),"北京");
File f=new File("d:"+File.separator+"boy.jpg");
InputStream input=new FileInputStream(f);
Blob image=Hibernate.getLobCreator(session).createBlob(input, input.available());
s.setImage(image);
session.save(s);
}
@Test
public void readImage() throws Exception{
Student s=(Student) session.get(Student.class, 1);
Blob image=s.getImage();
InputStream input=image.getBinaryStream();
File f=new File("d:"+File.separator+"girl.jpg");
OutputStream output=new FileOutputStream(f);
byte[] buff=new byte[input.available()];
input.read(buff);
output.write(buff);
output.close();
input.close();
}
对象类型:
图片上传到数据库
hibernate-对象类型
对象类型1
1.clob和text对应大文本文件,blob对应大的二进制文件,例如视频音频图片 2.java中的clob对应存储大文本文件,java中的blob对应存储大二进制文件 MySQL不支持标准SQL的CLOB类型,在Mysql中,用TEXT,MEDIUMTEXT及LONGTEXT类型来表示长度超过255的长文本数据 获取照片文件的写法 File f=new File("照片的地址"+File.separator+"照片名字"); InputStream input =new FileInputStream(f); Blob image=Hibrbate.getLobCreator(session).createBlob(input,input.available()); s.setpPicture(image); session.save(s);
可以结合最初学的io流的读取与写入
对象类型
保存照片:将照片转换为大二进制文件Blob,存到Hibernate数据库
对象映射关系