日期:2014-05-17 浏览次数:20743 次
package com.hiernate.util;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hiernate.persistence.*;
//hibernate工具类,于数据库交互.
public class HibernateUtil {
static private Session session;
static GetHibernate hib = new GetHibernate(); //创建
// 按照用户名和密码寻找用户
public static List findUser(String strUserName, String strPwd) {
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类的开启session方法.
tx = (Transaction) session.beginTransaction(); //开启事物
Query query = session.createQuery("from User as u where u.userName=:strUserName and u.pwd=:strPwd"); //应用HQL检索查找满足条件的集合
query.setString("strUserName", strUserName); //动态绑定参数
query.setString("strPwd", strPwd);
list = query.list(); //list方法用来执行HQL语句
tx.commit(); //事务的提交
hib.closeSession(session); //关闭session
} catch (Exception e) {
e.printStackTrace(); //输出异常信息
tx.rollback(); //事务的回滚
}
return list;
}
// 查出所有用户并分页
public static List findUser(int recPerPage,int pages) {
Transaction tx = null;
List list = null;
try {
session = hib.openSession();
tx = (Transaction) session.beginTransaction();
Query query = session.createQuery("from User");
query.setFirstResult(recPerPage);
query.setMaxResults(pages);
list = query.list();
tx.commit();
hib.closeSession(session);