一、基本类型:
二、对象类型:
三、BLOB类型的读写操作:
【
PictureTest.java】
public
class
PictureTest {
private
SessionFactory
sessionFactory
;
private
Session
session
;
private
Transaction
transaction
;
@Before
public
void
init(){
//创建配置对象
Configuration config=
new
Configuration().configure();
//创建服务配置对象
ServiceRegistry serviceRegistry=
new
ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建会话工厂对象
sessionFactory
=config.buildSessionFactory(serviceRegistry);
//创建会话对象
session
=
sessionFactory
.openSession();
//开启事务
transaction
=
session
.beginTransaction();
}
@After
public
void
destroy(){
//提交事务
transaction
.commit();
//关闭会话
session
.close();
//关闭会话工厂
sessionFactory
.close();
}
@Test
public
void
testSavePicture()
throws
Exception{
String picPath=getWebRootPath()+
"/image/pic1.jpg"
;
//获得图片文件
File file=
new
File(picPath);
//获得图片文件的输入流
InputStream inputStream=
new
FileInputStream(file);
//创建BLOB对象
Blob headPicture=Hibernate.getLobCreator(
session
).createBlob(inputStream, inputStream.available());
Picture picture=
new
Picture();
//设置学号
picture.setSno(
"20121120162"
);
//设置头像
picture.setHead(headPicture);
session
.save(picture);
}
@Test
public
void
testReadPicture()
throws
Exception{
Picture picture=
new
Picture();
picture=(Picture)
session
.get(Picture.
class
, 1);
Blob headPicture=picture.getHead();
InputStream inputStream=headPicture.getBinaryStream();
byte
buffer[]=
new
byte
[inputStream.available()];
File file=
new
File(getWebRootPath()+
"/image/pic2.jpg"
);
OutputStream outputStream=
new
FileOutputStream(file);
inputStream.read(buffer);
outputStream.write(buffer);
inputStream.close();
outputStream.close();
}
private
String getWebRootPath(){
ClassLoader classLoader = Thread. currentThread()
.getContextClassLoader();
if
(classLoader ==
null
) {
classLoader = ClassLoader. getSystemClassLoader();
}
java.net.URL url = classLoader.getResource(
""
);
String ROOT_CLASS_PATH = url.getPath() +
"/"
;
File rootFile =
new
File(ROOT_CLASS_PATH);
String WEB_INFO_DIRECTORY_PATH = rootFile.getParent() +
"/"
;
File webInfoDir =
new
File(WEB_INFO_DIRECTORY_PATH);
String SERVLET_CONTEXT_PATH = webInfoDir.getParent() +
"/"
;
//这里 SERVLET_CONTEXT_PATH 就是WebRoot的路径
String path = SERVLET_CONTEXT_PATH;
path = path.replaceAll(
"%20"
,
" "
);
return
path;
}
}