存放图片的核心代码
try {
User u = new User();
u.setName("小冥王");
File f = new File("D:"+File.separator+"m.jpg");
//获得照片文件的输入流
InputStream input = new FileInputStream(f);
byte[] b = new byte[input.available()];
input.read(b);
Blob blob = session.getLobHelper().createBlob(b);
u.setImage(blob);
session.save(u);
tran.commit();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
读取到本地的核心代码:
try {
String hql ="from User where id = 1";
Query q = session.createQuery(hql);
User u = (User) q.list().get(0);
System.out.println(u.getName());
Blob blob = u.getImage();
File file = new File("E:/test/m.jpg");
InputStream is = blob.getBinaryStream();
byte[] b = new byte[1024];
OutputStream os = new FileOutputStream(file);
while (is.read(b)!= -1) {
os.write(b);
}
os.close();
is.close();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}