Commit 8f2b65ad by zhangyang

feat:[none] 调用sessionTemplate统一改成方法形式以便子类自定义

parent 34ab6f0e
package com.pcloud.common.core.dao; package com.pcloud.common.core.dao;
import java.sql.Connection; import java.sql.Connection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.string.StringUtil;
import org.apache.ibatis.jdbc.SqlRunner; import org.apache.ibatis.jdbc.SqlRunner;
import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
import com.pcloud.common.core.mybatis.interceptor.ExecutorInterceptor; import com.pcloud.common.core.mybatis.interceptor.ExecutorInterceptor;
import com.pcloud.common.entity.BaseEntity; import com.pcloud.common.entity.BaseEntity;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBean; import com.pcloud.common.page.PageBean;
import com.pcloud.common.page.PageBeanNew; import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam; import com.pcloud.common.page.PageParam;
/** /**
* @描述:数据访问层基础支撑类. @作者:DiSeng.H * @描述:数据访问层基础支撑类. @作者:DiSeng.H
* @创建时间:2016年3月11日,下午4:03:36 @版本:1.0 * @创建时间:2016年3月11日,下午4:03:36 @版本:1.0
*/ */
public abstract class BaseDaoImpl<T extends BaseEntity> implements BaseDao<T> { public abstract class BaseDaoImpl<T extends BaseEntity> implements BaseDao<T> {
protected static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class); protected static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
public static final String SQL_INSERT = "insert"; public static final String SQL_INSERT = "insert";
public static final String SQL_BATCH_INSERT = "batchInsert"; public static final String SQL_BATCH_INSERT = "batchInsert";
public static final String SQL_UPDATE = "update"; public static final String SQL_UPDATE = "update";
public static final String SQL_GET_BY_ID = "getById"; public static final String SQL_GET_BY_ID = "getById";
public static final String SQL_DELETE_BY_ID = "deleteById"; public static final String SQL_DELETE_BY_ID = "deleteById";
public static final String SQL_LIST_PAGE = "listPage"; public static final String SQL_LIST_PAGE = "listPage";
public static final String SQL_LIST_BY = "listBy"; public static final String SQL_LIST_BY = "listBy";
public static final String SQL_COUNT_BY_PAGE_PARAM = "countByPageParam"; // 根据当前分页参数进行统计 public static final String SQL_COUNT_BY_PAGE_PARAM = "countByPageParam"; // 根据当前分页参数进行统计
/** /**
* 注入SqlSessionTemplate实例(要求Spring中进行SqlSessionTemplate的配置).<br/> * 注入SqlSessionTemplate实例(要求Spring中进行SqlSessionTemplate的配置).<br/>
* 可以调用sessionTemplate完成数据库操作. * 可以调用sessionTemplate完成数据库操作.
*/ */
@Autowired @Autowired
protected SqlSessionTemplate sqlSessionTemplate; protected SqlSessionTemplate sqlSessionTemplate;
@Autowired @Autowired
protected SqlSessionFactory sqlSessionFactory; protected SqlSessionFactory sqlSessionFactory;
@Autowired @Autowired
private DruidDataSource druidDataSource; private DruidDataSource druidDataSource;
public SqlSessionTemplate getSessionTemplate() { public SqlSessionTemplate getSessionTemplate() {
return sqlSessionTemplate; return sqlSessionTemplate;
} }
public SqlSession getSqlSession() { public SqlSessionFactory getSqlSessionFactory() {
return sqlSessionTemplate; return sqlSessionFactory;
} }
public long insert(T t) { public SqlSession getSqlSession() {
return sqlSessionTemplate;
if (t == null) }
throw new RuntimeException("T is null");
public long insert(T t) {
int result = sqlSessionTemplate.insert(getStatement(SQL_INSERT), t);
if (t == null)
if (result <= 0) throw new RuntimeException("T is null");
throw BizException.DB_INSERT_RESULT_0;
int result = getSessionTemplate().insert(getStatement(SQL_INSERT), t);
if (t != null && t.getId() != null && result > 0)
return t.getId(); if (result <= 0)
throw BizException.DB_INSERT_RESULT_0;
return result;
} if (t != null && t.getId() != null && result > 0)
return t.getId();
public long insert(List<T> list) {
return result;
if (list == null || list.size() <= 0) }
return 0;
public long insert(List<T> list) {
int result = sqlSessionTemplate.insert(getStatement(SQL_BATCH_INSERT), list);
if (list == null || list.size() <= 0)
if (result <= 0) return 0;
throw BizException.DB_INSERT_RESULT_0;
int result = getSessionTemplate().insert(getStatement(SQL_BATCH_INSERT), list);
return result;
} if (result <= 0)
throw BizException.DB_INSERT_RESULT_0;
public long update(T t) {
if (t == null) return result;
throw new RuntimeException("T is null"); }
int result = sqlSessionTemplate.update(getStatement(SQL_UPDATE), t); public long update(T t) {
if (t == null)
if (result <= 0) throw new RuntimeException("T is null");
throw BizException.DB_UPDATE_RESULT_0;
int result = getSessionTemplate().update(getStatement(SQL_UPDATE), t);
return result;
} if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
public long update(T t, String sqlId) {
if (t == null) return result;
throw new RuntimeException("T is null"); }
int result = 0; public long update(T t, String sqlId) {
try { if (t == null)
result = sqlSessionTemplate.update(getStatement(sqlId), t); throw new RuntimeException("T is null");
} catch (Exception e) {
logger.error("update fail[" + sqlId + "]:" + e.getMessage(), e); int result = 0;
throw BizException.DB_DML_FAIL; try {
} result = getSessionTemplate().update(getStatement(sqlId), t);
if (result <= 0) } catch (Exception e) {
throw BizException.DB_UPDATE_RESULT_0; logger.error("update fail[" + sqlId + "]:" + e.getMessage(), e);
throw BizException.DB_DML_FAIL;
return result; }
} if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
public long update(T t, String sqlId, String errorMessage) {
if (t == null) return result;
throw new RuntimeException("T is null"); }
int result = 0; public long update(T t, String sqlId, String errorMessage) {
try { if (t == null)
result = sqlSessionTemplate.update(getStatement(sqlId), t); throw new RuntimeException("T is null");
} catch (Exception e) {
logger.error("update fail[" + sqlId + "]:" + e.getMessage(), e); int result = 0;
throw BizException.DB_DML_FAIL; try {
} result = getSessionTemplate().update(getStatement(sqlId), t);
if (result <= 0) { } catch (Exception e) {
if (StringUtil.isEmpty(errorMessage)) logger.error("update fail[" + sqlId + "]:" + e.getMessage(), e);
throw BizException.DB_UPDATE_RESULT_0; throw BizException.DB_DML_FAIL;
else }
throw new BizException(10000, errorMessage); if (result <= 0) {
} if (StringUtil.isEmpty(errorMessage))
throw BizException.DB_UPDATE_RESULT_0;
return result; else
} throw new BizException(10000, errorMessage);
}
public long update(List<T> list) {
return result;
if (list == null || list.size() <= 0) }
return 0;
public long update(List<T> list) {
int result = 0;
if (list == null || list.size() <= 0)
for (int i = 0; i < list.size(); i++) { return 0;
this.update(list.get(i));
result += 1; int result = 0;
}
for (int i = 0; i < list.size(); i++) {
if (result <= 0) this.update(list.get(i));
throw BizException.DB_UPDATE_RESULT_0; result += 1;
}
return result;
} if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
public T getById(long id) {
return sqlSessionTemplate.selectOne(getStatement(SQL_GET_BY_ID), id); return result;
} }
public long deleteById(long id) { public T getById(long id) {
return (long) sqlSessionTemplate.delete(getStatement(SQL_DELETE_BY_ID), id); return getSessionTemplate().selectOne(getStatement(SQL_GET_BY_ID), id);
} }
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId) { public long deleteById(long id) {
return (long) getSessionTemplate().delete(getStatement(SQL_DELETE_BY_ID), id);
if (paramMap == null) }
paramMap = new HashMap<String, Object>();
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap, if (paramMap == null)
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage())); paramMap = new HashMap<String, Object>();
// 统计总记录数 // 获取分页数据集 , 注切勿换成 sessionTemplate 对象
Object countObject = (Object) getSqlSession().selectOne(getStatement(sqlId), List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new ExecutorInterceptor.CountParameter(paramMap)); new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
Long count = Long.valueOf(countObject.toString());
// 统计总记录数
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list); Object countObject = (Object) getSqlSession().selectOne(getStatement(sqlId),
} new ExecutorInterceptor.CountParameter(paramMap));
Long count = Long.valueOf(countObject.toString());
public <C> PageBeanNew<C> listPageNew(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
if (paramMap == null) return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
paramMap = new HashMap<String, Object>(); }
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象 public <C> PageBeanNew<C> listPageNew(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
List<C> list = getSqlSession().selectList(getStatement(sqlId), paramMap, if (paramMap == null)
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage())); paramMap = new HashMap<String, Object>();
// 统计总记录数 // 获取分页数据集 , 注切勿换成 sessionTemplate 对象
Integer count = getSqlSession().selectOne(getStatement(sqlId), List<C> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new ExecutorInterceptor.CountParameter(paramMap)); new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
return new PageBeanNew<C>(pageParam.getPageNum(), pageParam.getNumPerPage(), count, list); // 统计总记录数
} Integer count = getSqlSession().selectOne(getStatement(sqlId),
new ExecutorInterceptor.CountParameter(paramMap));
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId, String countSqlId) {
return new PageBeanNew<C>(pageParam.getPageNum(), pageParam.getNumPerPage(), count, list);
if (paramMap == null) }
paramMap = new HashMap<String, Object>();
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId, String countSqlId) {
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap, if (paramMap == null)
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage())); paramMap = new HashMap<String, Object>();
// 统计总记录数 // 获取分页数据集 , 注切勿换成 sessionTemplate 对象
Object countObject = getSqlSession().selectOne(getStatement(countSqlId), paramMap); List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
Long count = Long.valueOf(countObject.toString()); new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list); // 统计总记录数
} Object countObject = getSqlSession().selectOne(getStatement(countSqlId), paramMap);
Long count = Long.valueOf(countObject.toString());
public <C> PageBeanNew<C> listPageNew(PageParam pageParam, Map<String, Object> paramMap, String sqlId,
String countSqlId) { return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
}
if (paramMap == null)
paramMap = new HashMap<String, Object>(); public <C> PageBeanNew<C> listPageNew(PageParam pageParam, Map<String, Object> paramMap, String sqlId,
String countSqlId) {
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<C> list = getSqlSession().selectList(getStatement(sqlId), paramMap, if (paramMap == null)
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage())); paramMap = new HashMap<String, Object>();
// 统计总记录数 // 获取分页数据集 , 注切勿换成 sessionTemplate 对象
Object countObject = getSqlSession().selectOne(getStatement(countSqlId), paramMap); List<C> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
Long count = Long.valueOf(countObject.toString()); new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
return new PageBeanNew<C>(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list); // 统计总记录数
} Object countObject = getSqlSession().selectOne(getStatement(countSqlId), paramMap);
Long count = Long.valueOf(countObject.toString());
public PageBean listSimplePage(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
return new PageBeanNew<C>(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
if (paramMap == null) }
paramMap = new HashMap<String, Object>();
public PageBean listSimplePage(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap, if (paramMap == null)
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage() + 1)); paramMap = new HashMap<String, Object>();
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), list); // 获取分页数据集 , 注切勿换成 sessionTemplate 对象
} List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage() + 1));
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) {
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), list);
if (paramMap == null) }
paramMap = new HashMap<String, Object>();
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) {
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(SQL_LIST_PAGE), paramMap, if (paramMap == null)
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage())); paramMap = new HashMap<String, Object>();
// 统计总记录数 // 获取分页数据集 , 注切勿换成 sessionTemplate 对象
Object countObject = (Object) getSqlSession().selectOne(getStatement(SQL_LIST_PAGE), List<Object> list = getSqlSession().selectList(getStatement(SQL_LIST_PAGE), paramMap,
new ExecutorInterceptor.CountParameter(paramMap)); new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
Long count = Long.valueOf(countObject.toString());
// 统计总记录数
// 是否统计当前分页条件下的数据:1:是,其他为否 Object countObject = (Object) getSqlSession().selectOne(getStatement(SQL_LIST_PAGE),
Object isCount = paramMap.get("isCount"); new ExecutorInterceptor.CountParameter(paramMap));
if (isCount != null && "1".equals(isCount.toString())) { Long count = Long.valueOf(countObject.toString());
Map<String, Object> countResultMap = sqlSessionTemplate.selectOne(getStatement(SQL_COUNT_BY_PAGE_PARAM),
paramMap); // 是否统计当前分页条件下的数据:1:是,其他为否
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list, Object isCount = paramMap.get("isCount");
countResultMap); if (isCount != null && "1".equals(isCount.toString())) {
} else { Map<String, Object> countResultMap = getSessionTemplate().selectOne(getStatement(SQL_COUNT_BY_PAGE_PARAM),
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list); paramMap);
} return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list,
} countResultMap);
} else {
@SuppressWarnings({"rawtypes", "unchecked"}) return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
public List<T> listBy(Map<String, Object> paramMap) { }
return (List) this.listBy(paramMap, SQL_LIST_BY); }
}
@SuppressWarnings({"rawtypes", "unchecked"})
public List<Object> listBy(Map<String, Object> paramMap, String sqlId) { public List<T> listBy(Map<String, Object> paramMap) {
if (paramMap == null) return (List) this.listBy(paramMap, SQL_LIST_BY);
paramMap = new HashMap<String, Object>(); }
return sqlSessionTemplate.selectList(getStatement(sqlId), paramMap); public List<Object> listBy(Map<String, Object> paramMap, String sqlId) {
} if (paramMap == null)
paramMap = new HashMap<String, Object>();
@SuppressWarnings("unchecked")
public T getBy(Map<String, Object> paramMap) { return getSessionTemplate().selectList(getStatement(sqlId), paramMap);
return (T) this.getBy(paramMap, SQL_LIST_BY); }
}
@SuppressWarnings("unchecked")
public Object getBy(Map<String, Object> paramMap, String sqlId) { public T getBy(Map<String, Object> paramMap) {
if (paramMap == null || paramMap.isEmpty()) return (T) this.getBy(paramMap, SQL_LIST_BY);
return null; }
return this.getSqlSession().selectOne(getStatement(sqlId), paramMap);
} public Object getBy(Map<String, Object> paramMap, String sqlId) {
if (paramMap == null || paramMap.isEmpty())
public String getStatement(String sqlId) { return null;
return this.getSqlSession().selectOne(getStatement(sqlId), paramMap);
String name = this.getClass().getName(); }
StringBuffer sb = new StringBuffer().append(name).append(".").append(sqlId); public String getStatement(String sqlId) {
return sb.toString(); String name = this.getClass().getName();
}
StringBuffer sb = new StringBuffer().append(name).append(".").append(sqlId);
/**
* 根据序列名称,获取序列值 return sb.toString();
*/ }
public String getSeqNextValue(String seqName) {
boolean isClosedConn = false; /**
// 获取当前线程的连接 * 根据序列名称,获取序列值
Connection connection = this.sqlSessionTemplate.getConnection(); */
// 获取Mybatis的SQLRunner类 public String getSeqNextValue(String seqName) {
SqlRunner sqlRunner = null; boolean isClosedConn = false;
try { // 获取当前线程的连接
// 要执行的SQL Connection connection = this.getSessionTemplate().getConnection();
String sql = ""; // 获取Mybatis的SQLRunner类
// 数据库驱动类 SqlRunner sqlRunner = null;
String driverClass = druidDataSource.getDriver().getClass().getName(); try {
// 不同的数据库,拼接SQL语句 // 要执行的SQL
if (driverClass.equals("com.ibm.db2.jcc.DB2Driver")) { String sql = "";
sql = " VALUES " + seqName.toUpperCase() + ".NEXTVAL"; // 数据库驱动类
} String driverClass = druidDataSource.getDriver().getClass().getName();
if (driverClass.equals("oracle.jdbc.OracleDriver")) { // 不同的数据库,拼接SQL语句
sql = "SELECT " + seqName.toUpperCase() + ".NEXTVAL FROM DUAL"; if (driverClass.equals("com.ibm.db2.jcc.DB2Driver")) {
} sql = " VALUES " + seqName.toUpperCase() + ".NEXTVAL";
if (driverClass.equals("com.mysql.jdbc.Driver")) { }
sql = "SELECT FUN_SEQ('" + seqName.toUpperCase() + "')"; if (driverClass.equals("oracle.jdbc.OracleDriver")) {
} sql = "SELECT " + seqName.toUpperCase() + ".NEXTVAL FROM DUAL";
// 如果状态为关闭,则需要从新打开一个连接 }
if (connection.isClosed()) { if (driverClass.equals("com.mysql.jdbc.Driver")) {
connection = sqlSessionFactory.openSession().getConnection(); sql = "SELECT FUN_SEQ('" + seqName.toUpperCase() + "')";
isClosedConn = true; }
} // 如果状态为关闭,则需要从新打开一个连接
sqlRunner = new SqlRunner(connection); if (connection.isClosed()) {
Object[] args = {}; connection = getSqlSessionFactory().openSession().getConnection();
// 执行SQL语句 isClosedConn = true;
Map<String, Object> params = sqlRunner.selectOne(sql, args); }
for (Object o : params.values()) { sqlRunner = new SqlRunner(connection);
return o.toString(); Object[] args = {};
} // 执行SQL语句
return null; Map<String, Object> params = sqlRunner.selectOne(sql, args);
} catch (Exception e) { for (Object o : params.values()) {
throw BizException.DB_GET_SEQ_NEXT_VALUE_ERROR.newInstance("获取序列出现错误!序列名称:{%s}", seqName); return o.toString();
} finally { }
if (isClosedConn) { return null;
sqlRunner.closeConnection(); } catch (Exception e) {
} throw BizException.DB_GET_SEQ_NEXT_VALUE_ERROR.newInstance("获取序列出现错误!序列名称:{%s}", seqName);
} } finally {
} if (isClosedConn) {
} sqlRunner.closeConnection();
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment