gistfile1.txt //User是一个javaBean,有id(int) name(String)两个字段,在数据库对应的表名是userimport java.util.List;import org.hibernate.Criteria;import org.hibernate.HibernateException;import org.hibernate.Session;impor
//User是一个javaBean,有id(int) name(String)两个字段,在数据库对应的表名是user import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import com.cn.domain.QueryResult; import com.cn.domain.User; import com.cn.utils.HibernateteUtils; public class UserDao { public void add(User user){ Session session =null; Transaction tx = null; try{ session = HibernateteUtils.getSession();//得到会话 tx = session.beginTransaction();//开启事务 session.save(user); tx.commit();//提交事务 }catch(Exception e){ tx.rollback(); throw e; }finally{ session.close();//释放资源 } } public void update(User user){ Session session = HibernateteUtils.getSession(); Transaction tx = null; try{ tx = session.beginTransaction(); session.update(user);//根据id更新 tx.commit(); }catch(RuntimeException e){ tx.rollback(); throw e; }finally{ session.close(); } } public void delete(int id){ Session session = HibernateteUtils.getSession(); Transaction tx = null; try { tx = session.beginTransaction(); Object user = session.get(User.class, id);//先找到对象在删除对象 session.delete(user); tx.commit(); } catch (HibernateException e) { tx.rollback(); throw new RuntimeException(e); } } public User find(int id){ Session session = HibernateteUtils.getSession(); Transaction tx = null; try { tx = session.beginTransaction(); User user = (User) session.get(User.class, id); tx.commit(); return user; } catch (HibernateException e) { session.close(); throw new RuntimeException(e); } } public ListfindAll(){ Session session = HibernateteUtils.getSession(); Transaction tx = null; try { tx = session.beginTransaction(); /* * 方式一 * List list = session.createQuery( "from User") .list();//User代表的是类,不是表名 */ //方式二 Criteria cri = session.createCriteria(User.class); //加限定条件 cri.add(Restrictions.between("id", 4, 10)); List list = cri.list(); tx.commit(); return list; } catch (HibernateException e) { tx.rollback(); throw new RuntimeException(e); }finally{ session.close(); } } public QueryResult findAll(int first,int max){ Session session = HibernateteUtils.getSession(); Transaction tx = null; try{ tx = session.beginTransaction(); /*Query query = session.createQuery("from user"); query.setFirstResult(first); query.setMaxResults(max);*/ List list = session.createQuery( "from User") .setFirstResult(first) .setMaxResults(max) .list(); Long count = (Long) session.createQuery( "select count(*) from User") .uniqueResult(); QueryResult result = new QueryResult(count.intValue(), list); tx.commit(); return result; }catch(Exception e){ tx.rollback(); throw new RuntimeException(e); }finally{ session.close(); } } }