packageorg.dao;importjava.util.List;importorg.bean.Userinfo;importorg.hibernate.Query;importorg.hibernate.Session;importorg.hibernate.Transaction;importorg.util.HibernateSessionFactory;public classUserDAO {publicSession session;//获得session方法
public voidgetCurrentSession(){//调用HibernateSessionFactory的getSession方法创建Session对象
session =HibernateSessionFactory.getSession();
}//关闭sesson方法
public voidcloseSession(){if(session != null){
HibernateSessionFactory.closeSession();
}
}//插入一条记录方法
public voidsave(String username,String password) {
Transaction t1=session.beginTransaction();
Userinfo userinfo= newUserinfo();
userinfo.setUsername(username);
userinfo.setPassword(password);
session.save(userinfo);
t1.commit();
}//修改这条方法
public void update(intid, String username){
Transaction t2=session.beginTransaction();
Userinfo userinfo= (Userinfo) session.get(Userinfo.class, id);
userinfo.setUsername(username);
session.update(userinfo);
t2.commit();
}//查询数据库结果方法
public voidqueryAllUser(){try{
Query query= session.createQuery("from Userinfo");
List list=query.list();for (int i = 0; i < list.size(); i++) {
Userinfo user=(Userinfo)list.get(i);
System.out.println(user.getId()+ " " +user.getUsername());
}
}catch(Exception e) {
e.printStackTrace();
}
}//删除该条记录方法
public void deleteUser(intid) {
Transaction t3=session.beginTransaction();
Userinfo userinfo= (Userinfo) session.get(Userinfo.class, id);
session.delete(userinfo);
t3.commit();
}
}