Hibernate数据库增删改查

来源:互联网 发布:seo金刚 编辑:程序博客网 时间:2024/04/29 22:07
package com.my.dao;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.lovo.util.HibernateUtil;
import com.my.bean.StudentBean;

public class StudentDao {
    
    Session session = HibernateUtil.getSession();
    Transaction tx=null;
    
    public List<StudentBean> showAllStudent() throws Exception{
        
        List<StudentBean> list= session.createQuery("from StudentBean").list();
        
        HibernateUtil.close();
        
        return list;
        
    }
    public void addStudent(StudentBean student)throws Exception{
        try {
             tx = session.beginTransaction();
             session.save(student);
             tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally{
            HibernateUtil.close();
        }
        
    }
    public boolean updateStudent(StudentBean student)throws Exception{
        
        try{  
           session=HibernateUtil.getSession();  
           tx=session.beginTransaction();  
           session.update(student);  
           tx.commit();  

          }catch(Exception e){  
              e.printStackTrace();  
          }finally{  
              if(session!=null){  
                  session.close();  
              }  
          }  
        return false;
    }
    
    public Boolean delStudent(int id)throws Exception{
        
        try{  
               StudentBean student = new StudentBean();
               session=HibernateUtil.getSession();  
               tx=session.beginTransaction();  
               student = (StudentBean) session.load(student.getClass(),id);
               session.delete(student);
               tx.commit();  

              }catch(Exception e){  
                  e.printStackTrace();  
              }finally{  
                  if(session!=null){  
                      session.close();  
                  }  
              }  
            return false;
    }
}


0 0