继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

hibernate中写入写出picture(Blob)的方法

dnswbglmnqwlsmn
关注TA
已关注
手记 2
粉丝 1
获赞 21

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.*;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

//测试类
public class StudentTest {

private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;

@Before
public void init(){
    //创建配置对象
    Configuration config=new Configuration().configure();
    //创建会话工厂对象
    sessionFactory=config.buildSessionFactory();
    //会话对象
    session=sessionFactory.openSession();
    //开启事务
    transaction =session.beginTransaction();

}

@After
public void destroy(){
    transaction.commit();//提交事务
    session.close();//关闭会话
    sessionFactory.close();//关闭会话工厂
}

//@Test
public void testSaveStudent(){

    //生成学生对象
    student s=new student( 0, "你的傻儿子", "男", new Date(),"守望之海");
    student s1=new student(1,"LG楠","男",new Date(),"守望之海");
    session.save(s);
    session.save(s1);//保存对象进数据库
}

//@Test
public void testWriteBlob() throws Exception
{
    student stu=new student(2,"达尼的双鱼","男",new Date(),"守望之海");
    //先获得照片文件
    File f=new File("E:"+File.separator+"test.jpg");
    //获得照片文件的输入流
    InputStream input=new FileInputStream(f);
    //创建一个Blob对象
    Blob image=Hibernate.getLobCreator(session).createBlob(input, input.available());
    //设置照片属性
    stu.setPicture(image);
    //保存学生
    session.save(stu);
}

@Test
public void testReadBlob() throws Exception
{
    student s=(student) session.get(student.class,2);
    //获得Blob对象
    Blob image=s.getPicture();
    //获得照片的输入流
    InputStream input=image.getBinaryStream();
    //创建输出流
    File file=new File("E:"+File.separator+"copy_test.jpg");
    //获得输出流
    OutputStream output=new FileOutputStream(file);
    //创建缓冲区
    byte[] buff=new byte[input.available()];
    input.read(buff);
    output.write(buff);
    input.close();
    output.close();
}

}

打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP

热门评论

有注释的代码真好,不过我还是不要知道你写的什么

查看全部评论