(%%%%%)struts+hibernate+oracle9i在删除程序中删除不了记录,请问是那的错(@@@@@@)
以下这样写对吗?
我的StudentDAOImp.java是这样写的
----------------------------------
public boolean deleteStudentByID(String id) {
// TODO Auto-generated method stub
try {
Session s = HibernateUtil.currentSession();
HibernateUtil.beginTransaction();
Userlist stu = (Userlist) s.load(Userlist.class, new Long(id));
HibernateUtil.commitTransaction();
System.out.println(stu.getId());
HibernateUtil.beginTransaction();
s.delete(stu);
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
return true;
} catch (HibernateException e) {
log.fatal(e);
}
return false;
}
HibernateUtil.java如下
----------------------------
public static void beginTransaction() {
System.out.println( "begin tx ");
Transaction tx = (Transaction) threadLocal.get();
try {
if (tx == null) {
tx = currentSession().beginTransaction();
threadLocal.set(tx);//tLocaltx
}
} catch (HibernateException e) {
// throw new InfrastructureException(e);
}
}
public static void commitTransaction() {
Transaction tx = (Transaction) threadLocal.get();
try {
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
tx.commit();
threadLocal.set(null);//tLocaltx
System.out.println( "commit tx ");
} catch (HibernateException e) {
// throw new InfrastructureException(e);
}
}
我的DeleteStudent.java是这样写的
---------------------------
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String id = (String)request.getParameter( "student_id ");
System.out.println( "iddddd= "+id);
stuDao = this.getStudentDAO();
if(!stuDao.deleteStudentByID(id)){
return (mapping.getInputForward());
}
return (mapping.findForward( "deleteStudentSuccess "));
}
[解决办法]
1、 多线hibernateutil不要作为全局来使用 将static去掉,为什么?因为如果是全局的话有可能当前线程要执行的事务的会话会被别的线程给关闭 这样无法达到事务的原子性。
2、将hibernateutil作为普通的对象引用放在StudentDAOImp中,即在StudentDAOImp中加入属
性:private HibernateUtil hutil = new HibernateUtil();
方法改成
public boolean deleteStudentByID(String id) {
// TODO Auto-generated method stub
try {
Session s = hutil.currentSession();
hutil.beginTransaction();
Userlist stu = (Userlist) s.load(Userlist.class, new Long(id));
//load有可能失败,可以试着把load改成get看看
hutil.commitTransaction(); //?好像可以不要
System.out.println(stu.getId());
hutil.beginTransaction();//?好像可以不要
s.delete(stu);
hutil.commitTransaction();
return true;
} catch (HibernateException e) {
log.fatal(e);
}finally{
hutil.closeSession();
}
return false;
}