Hibernate可以保存图片到数据库中的Blob类型中,详细请看代码吧。
1、存图片到数据库中:
TestPerson thisA = new TestPerson(); // 因为hibernate不是自动提交,因此需要创建事务
Transaction t = thisA.session.beginTransaction();
Person p = new Person(); // 创建POJO
p.setName("wll");
p.setAge(21);
p.setPhoto(Hibernate.createBlob(new FileInputStream("C://1.png")));
thisA.session.save(p); // POJO-->PO
t.commit(); // 提交事务
2、从数据库中获取图片:
PersonDAO pDAO = new PersonDAO();
//只获取第一张图片好了
Person person = (Person) pDAO.findAll().get(0);
Blob blob = person.getPhoto();
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream("C://2.png");
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();