一个Dao类


package cn.yicha.adunion.dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class BaseDao {
private final static Logger logger = Logger.getLogger(BaseDao.class);


public boolean save(final Object entity) {
Session sn = null;
boolean flag = false;
try {
sn = SessionManager.getSession();
Transaction ts = sn.beginTransaction();
sn.save(entity);
ts.commit();
flag = true;
} catch (Exception ex) {
flag = false;
logger.error("save() error:" + ex.getMessage(), ex);
} finally {
SessionManager.closeSession();
}
return flag;
}

public boolean update(final Object entity) {
Session sn = null;
boolean flag = false;
try {
sn = SessionManager.getSession();
Transaction ts = sn.beginTransaction();
sn.update(entity);
ts.commit();
flag = true;
} catch (Exception ex) {
flag = false;
logger.error("update() error:" + ex.getMessage(), ex);
} finally {
SessionManager.closeSession();
}
return flag;
}

public boolean delete(final Object entity) {
Session sn = null;
boolean flag = false;
try {
sn = SessionManager.getSession();
Transaction ts = sn.beginTransaction();
sn.delete(entity);
ts.commit();
flag = true;
} catch (Exception ex) {
flag = false;
logger.error("delete() error:" + ex.getMessage(), ex);
} finally {
SessionManager.closeSession();
}
return flag;
}

public Object get(final Class entity, final Serializable id) {
Session sn = null;
Object obj = null;
try {
sn = SessionManager.getSession();

obj = sn.get(entity, id);

} catch (Exception ex) {
logger.error("get() error:" + ex.getMessage(), ex);
} finally {
SessionManager.closeSession();
}
return obj;
}

public List findAll(final Class entity) {
Session sn = null;
List list = null;
try {
sn = SessionManager.getSession();
//Transaction ts = sn.beginTransaction();
list = sn.createQuery(" from " + entity.getName()).list();
//ts.commit();
} catch (Exception ex) {
logger.error("find() error:" + ex.getMessage(), ex);
} finally {
SessionManager.closeSession();
}
return list;
}

public List find(final String query) {
Session sn = null;
List list = null;
try {
sn = SessionManager.getSession();
//Transaction ts = sn.beginTransaction();
list = sn.createQuery(query).list();
//ts.commit();
} catch (Exception ex) {
logger.error("find() error:" + ex.getMessage(), ex);
} finally {
SessionManager.closeSession();
}
return list;
}

public List find(final String queryStr, final Object[] parameter) {
Session sn = null;
List list = null;
try {
sn = SessionManager.getSession();
//Transaction ts = sn.beginTransaction();
Query query = sn.createQuery(queryStr);
int len = parameter.length;
for (int i = 0; i < len; i++) {
query.setParameter(i, parameter[i]);
}
list = query.list();

//ts.commit();
} catch (Exception ex) {
logger.error("find error:" + ex.getMessage(), ex);
} finally {
SessionManager.closeSession();
}
return list;
}

/**
* 用标准Sql语句查询数据库
* @param sql sql语句
* @return
*/
public List selectWithSql(String sql){
Session sn = null;
try {

sn = SessionManager.getSession();
Transaction ts = sn.beginTransaction();
ts.begin();
SQLQuery query = sn.createSQLQuery(sql);
List l = query.list();
ts.commit();
return l;
}finally{
SessionManager.closeSession();
}
}

/**
* 得到分页的结果
* @param currentPage : 当前页
* @param pageSize : 每页要显示多少条数据
* @param countSql : 统计Hql
* @param countValues : 统计Hql中的值(是一个对象数组)
* @param sql
* @param values
* @return
*/
public HashMap getPageResult(int currentPage, final int pageSize
,final String countHql,final Object[] countValues, final String hql,final Object[] values) {

HashMap map = new HashMap();
List list=new ArrayList();

int totalSize= getTotalSize(countHql,countValues);

int start = 0; //第currentPage页数据是从哪条记录开始的
int end = 0; //第currentPage页数据是从哪条记录结束的
int totalPage = 0;


/***** 找出当前要显示页(currentpage)的开始记录号"start"和结束记录号"end",以便只把当前页的数据给找出来 ******/
totalPage = (int)Math.ceil((double)totalSize/pageSize); //共有多少页
//System.out.println("total:"+total+" totalPage:"+totalPage+" currentPage:"+currentPage);
//如果当前页大于总页数,则显示最后一页
if(currentPage>totalPage) currentPage = totalPage;
//如果当前页小于0,则显示第一页
if(currentPage<1) currentPage = 1;

// 根据条件判断,取出所需记录
start = pageSize*(currentPage-1);
end = start + pageSize;
if(end>totalSize) end = totalSize; //因为在下面的循环中用到的是小于,所以在此用"="



list = getCurrentPageResult(start,pageSize,hql,values);


map.put("list",list);
map.put("currentPage",String.valueOf(currentPage));
map.put("totalPage",String.valueOf(totalPage));
map.put("pageSize", String.valueOf(pageSize));
map.put("totalSize", String.valueOf(totalSize));

return map;

}

private int getTotalSize(String countHql,Object[] countValues){
Session session = SessionManager.getSession();
Query query = session.createQuery(countHql);

if(countValues!=null){
for (int i = 0; i < countValues.length; i++) {
String type = getType(countValues[i].getClass().getName());
if (type.equals("String")) {
query.setString(i, "%" + countValues[i].toString() + "%");
}else if (type.equals("Date")) {
query.setDate(i, (Date)countValues[i]);
}else if (type.equals("int")) {
query.setInteger(i, Integer.parseInt((countValues[i].toString())));
}else if (type.equals("Boolean")) {
query.setBoolean(i, Boolean.getBoolean(countValues[i].toString()));
}
}
}
return Integer.parseInt(query.uniqueResult().toString());
}

/**
* 功能:得到分页的结果(当前页)
* @param start : 开始记录号
* @param pageSize : 每页显示多少条记录
* @param sql : 要查询的sql语句
* @param values : sql语句中的变量值
* @return
*/
private List getCurrentPageResult(final int start,final int pageSize,final String sql,final Object[] values){

Session session = SessionManager.getSession();

Query query = session.createQuery(sql);

if(values!=null){
for (int i = 0; i < values.length; i++) {
String type = getType(values[i].getClass().getName());
if (type.equals("String")) {
query.setString(i, "%" + values[i].toString() + "%");
}else if (type.equals("Date")) {
query.setDate(i, (Date)values[i]);
}else if (type.equals("int")) {
query.setInteger(i, Integer.parseInt(values[i].toString()));
}else if (type.equals("Boolean")) {
query.setBoolean(i, Boolean.getBoolean(values[i].toString()));
}
}
}

query.setFetchSize(30);
query.setFirstResult(start);
query.setMaxResults(pageSize);

return query.list();
}


/**
* jiangys, 2008-01-24
* 查询数据库,并根据页数和页面显示数返回结果集
* @param hql 查询语句
* @param pageSize 页面显示数
* @param pageNum 页数
* @return
*/
public List find(final String hql, int pageSize, int pageNum) {
Session sn = null;
List list = null;
try {
sn = SessionManager.getSession();
Query query = sn.createQuery(hql);
int first = 0;
int last = 0;

if(pageNum <= 1){
first = 0;
last = pageSize;
}else{
first = (pageNum - 1) * pageSize;
last = pageSize * pageNum;
}

query.setFirstResult(first);
query.setMaxResults(last);
list = query.list();
} catch (Exception ex) {
logger.error("find() error:" + ex.getMessage(), ex);
} finally {
SessionManager.closeSession();
}
return list;
}

private String getType(String typeParam) {
int last = typeParam.lastIndexOf(".");
return typeParam.substring(last + 1);
}


/**
* 执行sql语句
* @param sql
* @return List HashMap
* @throws YiChaAdException
*/
public List executeQuery(String sql){
Session sn = null;
ResultSet rs = null;
List list = null;
try {
sn = SessionManager.getSession();
Connection conn=sn.connection();
rs = conn.createStatement().executeQuery(sql);
list = getList(rs);
}catch(Exception e){
logger.error("executeQuery :"+e.getMessage(),e);
}finally{
SessionManager.closeSession();
}

return list;
}

/**
* 执行sql语句
* @param sql
* @return boolean
*/
public boolean executeSql(String sql){
boolean result=false;
Session sn = null;
logger.info(sql);
try {
sn = SessionManager.getSession();
Connection conn=sn.connection();
conn.setAutoCommit(false);
conn.createStatement().executeUpdate(sql);
conn.commit();

result=true;
}catch(Exception e){
logger.error("execute:" + sql + e.getMessage(),e);
}finally{
SessionManager.closeSession();
}

return result;
}


/*
* @由rs得到ArrayList
*/
ArrayList getList(ResultSet rs) {
ArrayList vector = new ArrayList();
ResultSetMetaData rsmd = null;
HashMap map = new HashMap();
int columnCount = 0;
try{
rsmd = rs.getMetaData();
columnCount = rsmd.getColumnCount();
String[] columnName = new String[columnCount];

for(int i=0;i<columnCount;i++){
columnName[i]=rsmd.getColumnName(i+1);
}
while(rs.next()){
map = new HashMap();
// System.out.println("rows:"+rs.getRow()+" id:"+rs.getInt("id")+" email:"+rs.getString("email"));
for(int i=0;i<columnCount;i++){
int type = rsmd.getColumnType(i + 1);
// System.out.println(columnName[i]+type);
try{
if(rs.getObject(i+1)==null)
map.put(columnName[i].toLowerCase(),null);
else{
switch (type) {
case 4: //integer型
map.put(columnName[i], Integer.valueOf(rs.getString(i+1)));
break;
case 91: //date型
map.put(columnName[i],rs.getDate(i+1));
break;
case 93: //datetime 或 timestamp
map.put(columnName[i],(Timestamp)rs.getObject(i+1));
break;
case -7: //boolean型
map.put(columnName[i],(Boolean)rs.getObject(i+1));
break;
default:
map.put(columnName[i],rs.getString(i+1));
}
}
}catch(Exception e){
map.put(columnName[i],"");
//System.out.println("列名:"+columnName[i]+"出错!"+e.getMessage().toString());
}
}
vector.add(map);
}
}catch(SQLException e){
logger.error("ProcessVO.java中的getVector()方法出错:"+e.getMessage());
}
return vector;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值