public class DAOImp {
static Session session=null;
/*------------创建新的学生对象-----------------*/
public static void createStu(Student stu) {
try {
session = HibernateUtil.currentSession(); //开启连接
Transaction tx = session.beginTransaction(); //开启事务
session.save(stu);
tx.commit();
} catch (HibernateException e) { //捕捉例外
e.printStackTrace();
}finally
{
HibernateUtil.closeSession(session);
}
}
/*------------获得学生对象-----------------*/
public static Student getStu(int id) {
Student stu = null;
try {
session = HibernateUtil.currentSession(); //开启连接
Transaction tx = session.beginTransaction(); //开启事务
stu = (Student) session.get(Student.class, id);
tx.commit();
} catch (HibernateException e) { //捕捉例外
e.printStackTrace();
}finally
{HibernateUtil.closeSession(session);}
return stu;
}
/*------------删除学生对象-----------------*/
public static void delStu(int id) {
try {
session = HibernateUtil.currentSession(); //开启连接
Transaction tx = session.beginTransaction(); //开启事务
Student stu = (Student) session.get(Student.class, id);
session.delete(stu);//删除对像
tx.commit();
} catch (HibernateException e) { //捕捉例外
e.printStackTrace();
}finally
{HibernateUtil.closeSession(session);}
}
/*------------修改学生对象-----------------*/
public static void mdfStu(Student stu) {
try {
session = HibernateUtil.currentSession(); //开启连接
Transaction tx = session.beginTransaction(); //开启事务
session.update(stu);
tx.commit();
} catch (HibernateException e) { //捕捉例外
e.printStackTrace();
}finally
{HibernateUtil.closeSession(session);}
}
/*------------取得所有的学生列表-----------------*/
public static List getAllStu() {
List list=null;
try {
session = HibernateUtil.currentSession(); //开启连接
Transaction tx = session.beginTransaction(); //开启事务
Query q=session.createQuery("from Student");
list=q.list();
tx.commit();
} catch (HibernateException e) { //捕捉例外
e.printStackTrace();
}finally
{
HibernateUtil.closeSession(session);
}
return list;
}
}
阅读(4310) | 评论(1) | 转发(0) |