hibernate的环境搭建(二)

2014-11-24 08:29:20 · 作者: · 浏览: 5
person.setAge(21);
person.setPwd("123321");
// 使用session保存person对象
session.save(person);
// 提交事务
transaction.commit();
} catch (Exception e) {
// 打印异常信息
e.printStackTrace();
// 回滚
transaction.rollback();
} finally {
// 关闭session
HibernateUtil.close(session);
}
}
// 查询id=2的person对象
@Test
public void testGet1() {
Session session = null;
// 查询操作,对 数据库的表没有任何修改,不用开启事务
try {
session = HibernateUtil.getSession();
// session.get()
Student person = (Student) session.get(Student.class, 3);
System.out.println("-------------------------------");
System.out.println(person.getId() + "," + person.getName());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
HibernateUtil.close(session);
}
}
// 使用load加载对象
@Test
public void testLoad1() {
Session session = null;
try {
session = HibernateUtil.getSession();
// 没有发出sql语句
// load():不会立刻去查询数据库,hibernate会返回一个代理对象
// 暂时代替person对象(避免对数据库过于频繁的访问,
// 提高 系统性能)
// hibernate 返回代理对象是cglib动态代理
// cglib返回是目标对象(Person)的子类对象
Student person = (Student) session.load(Student.class, 1);
System.out.println("-------------------");
// 真正需要访问数据的时候
// 发出了sql语句,person发出的sql语句
// hibernate返回的代理对象发出对应sql语句
System.out.println(person.getName());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
HibernateUtil.close(session);
}
}
// get()查询的数据,在数据库中不存在
// 返回null
@Test
public void testGet2() {
Session session = null;
try {
session = HibernateUtil.getSession();
Student person = (Student) session.get(Student.class, 2);
System.out.println(person);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
HibernateUtil.close(session);
}
}
// load()查询数据库中没有的数据
// 如果数据库中没有与之对应的数据,则抛出
// ObjectNotFoundException
// 常见异常:SQLException / HibernateException / NestableRuntimeException
@Test
public void testLoad2() {
Session session = null;
try {
session = HibernateUtil.getSession();
Student person = (Student) session.load(Student.class, 2);
System.out.println(person);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
HibernateUtil.close(session);
}
}
// load:需要的时候才发出sql语句,去数据库中真实的查询
// 这叫做延迟加载/懒加载(预习)
// proxy:代理
// org.hibernate.LazyInitializationException:
// could not initialize proxy - no Session
// hibernate.load()返回的代理对象的生命周期跟session保持一致
// 关闭session,代理对象也不能使用了,不能发出sql语句
@Test
public void testLoad3() {
Session session = n