package com.yuzd.hibernate;import java.util.Date;import junit.framework.TestCase;import org.hibernate.Session;import com.yuzd.util.HbmUtils;public class SessionTest extends TestCase { public void addUser(){ Session session = null; try { session = HbmUtils.getSession(); session.beginTransaction(); User user = new User(); user.setName("aaa"); user.setPassword("aaa"); user.setCreateTime(new Date()); user.setExpireTime(new Date()); session.save(user); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally{ HbmUtils.closeSession(session); } } public void getUser(){ Session session =null; try { session = HbmUtils.getSession(); session.beginTransaction(); //get方法是通过主键id来查找的,hibernate中get方法建议在事物中使用 //如果get方法查询不出结果则返回null User user = (User) session.get(User.class, "402881e941c503b30141c503b7440001"); System.out.println(user.getName()); user.setName("李四"); session.save(user); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally{ HbmUtils.closeSession(session); } } public void loadUser(){ Session session = null; try { session = HbmUtils.getSession(); session.beginTransaction(); //只有在真正使用的时候才会发出sql指令,lazy延迟加载 //如果数据库中没有对应的数据的话就会抛出异常 User user = (User) session.load(User.class, "402881e941c5a1630141c5a482330001"); System.out.println(user.getName());//这句的时候才会真正的去数据库查询 session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally{ HbmUtils.closeSession(session); } } public void updateUser(){ Session session = null; try { session = HbmUtils.getSession(); session.beginTransaction(); User user = new User(); user.setId("402881e941c5a1630141c5a482330001"); user.setName("王五"); //这样改的话会把其他的属性设置成null,一般采用的方法是先load然后更改属性值 session.update(user); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally{ HbmUtils.closeSession(session); } } public void deleteUser(){ Session session = null; try { session = HbmUtils.getSession(); session.beginTransaction(); //先load然后再delete User user = (User) session.load(User.class, "402881e941c5a1630141c5a482330001"); session.delete(user); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally{ HbmUtils.closeSession(session); } }}