Hibernate初探之单表映射
本文为学习时所做笔记,不足之处,欢迎指正。
主要内容:
- 单一主键
- 基本类型
- 对象类型
- 组件属性
- 单表操作CRUD实例
单一主键(以MySQL为例)
assigned : 由Java应用程序负责生成(手工赋值)
native : 由底层数据库自动生成标示符,如果是MySQL就是increment,如果是Oracle就是sequence,等等
基本类型
对象类型
注:MySQL不支持SQL的CLOB类型,在MySQL中,用TEXT、MEDIUMTEXT、LONGTEXT类型表示长度超过155的长文本数据
写入Blob,如图片,视频等
public void testWriteBlob() throws Exception{
Student student = new Student();
//获得照片文件
File file = new File("d:"+File.separator+"image.jpg");
//获得照片文件输入流
InputStream input = new FileInputStream(file);
//创建Blob对象
Blob image = Hibernate.getLobCreator(session).createBlob(input,input.available());
//将图片保存在对象中
student.setPicture(image);
//保存对象
session.save(student);
}
读取Blob
public void testReadBlob() throws Exception{
Student student = (Student) session.get(Student.class,1);
//获得Blob对象
Blob image = student.getPicture();
//获得照片的输入流
InputStream input = iamge.getBinaryStream();
//创建输出流
File file = new File("d:"+File.separator+"dest.jpg");
//OutputStream output = new FileOutputStream(file);
//创建缓冲区
byte[] buffer = new byte[input.available()];
input.read(buffer);
output.write(buffer);
input.close();
output.close();
}
组件属性
实体类中的某个属性属于用户自定义的类的对象
<component name = "address" class = "Address">
<property name = "postcode" column="POSTCODE"></property>
<property name = "phone" column = "PHONE"></property>
<property name = "address" column = "ADDRESS"></property>
</component>
单表操作CRUD实例
- save
- update
- delete
- get/load(查询单个记录)
public void testSaveStudent(){
Student student = new Student();
session.save(student);
}
public void testGetStudent(){
Student student = (Student) session.get(Student.class,100);
/* get参数
* 第一个参数:类对象,待查询表属于哪个类,利用反射获得
* 第二个参数:标识符,待查询记录的主键
*/
System.out.println(Student);
}
public void testLoadStudent(){
Student student = (Student) session.load(Student.class,100);
/* get参数
* 第一个参数:类对象,待查询表属于哪个类,利用反射获得
* 第二个参数:标识符,待查询记录的主键
*/
System.out.println(Student);
}
public void testUpdateStudent(){
Student student = (Student) session.get(Student.class,100);
/* get参数
* 第一个参数:类对象,待查询表属于哪个类,利用反射获得
* 第二个参数:标识符,待查询记录的主键
*/
student.setName("Bob"); //更改学生信息
session.update(student);
}
public void testDeleteStudent(){
Student student = (Student) session.get(Student.class,100);
/* get参数
* 第一个参数:类对象,待查询表属于哪个类,利用反射获得
* 第二个参数:标识符,待查询记录的主键
*/
session.delete(student);
}
get和load的区别
在不考虑缓存的情况下,get方法会在调用之后立即向数据库发出sql语句,返回持久化对象。load方法会在调用后返回一个代理对象,该代理对象只保存了实体对象的id,直到使用对象的非主键属性时才会发出sql语句
查询数据库中不存在的数据时,get方法返回null,load方法抛出异常org.hibernate.ObjectNotFoundException