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();
}
}
点击查看更多内容
3人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦