增删改查
直接上代码
事务回滚放在后面 分层 因为是Test测试 每次测试完毕会释放内存 就算出现异常 资源没有关闭也不会影响 ,但是在正常项目中要关闭资源 保存操作即正确操作 ,出现异常进行回滚
get 与 load的区别
load 懒加载 结果是实体的代理类
get 查询就加载 结果是实体类
/**
* 测试保存
*/
@Test
public void testSave() {
//事务问题
Customer customer = new Customer();
customer.setCustName("测试保存功能");
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.openSession();
tx = session.beginTransaction();
session.save(customer);
tx.commit();
} catch (Exception e) {
tx.rollback();
} finally {
session.close();
}
}
/**
* 测试修改
*/
@Test
public void testUpdate() {
Session session = HibernateUtils.openSession();
Transaction tx = session.beginTransaction();
Customer customer = session.get(Customer.class, 94L);
customer.setCustAddress("北京天安门");
customer.setCustPhone("15666667662");
customer.setCustLevel("超级测试级别");
session.update(customer);
tx.commit();
session.close();
}
/**
* 测试删除 删除必须传一个实体
*/
@Test
public void testDelete() {
Session session = HibernateUtils.openSession();
Transaction tx = session.beginTransaction();
Customer customer = session.get(Customer.class, 95L);
session.delete(customer);
tx.commit();
session.close();
}
/**
* 测试查询
*/
@Test
public void testFindOne() {
Session session = HibernateUtils.openSession();
Transaction tx = session.beginTransaction();
Customer customer = session.get(Customer.class, 94L);
System.out.println(customer.getCustName());
tx.commit();
session.close();
}
@Test
public void testFinaAll() {
Session session = HibernateUtils.openSession();
Transaction tx = session.beginTransaction();
SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM cst_customer");
List<Object[]> list = sqlQuery.list();
for(Object[] os : list){
System.out.println("数组内容 " + os);
for (Object o : os) {
System.out.println("object 内容" + o);
}
}
}