实例:
可考虑做两部封装,
1.对从数据库连接池中获取的sqlSession封装成sqlSessionTemplate对象,是的用户不需要关心数据连接的获取过程
2.对mybatis获取mapp.xml的过程进行封装,即用户只需要关心传入表名称和sql语句,另外对sqlSession提供的原始方法封装,如crud,selectOne,selectList
首先对sqlSession进行封装,封装出一个可用的SqlSessionTemplate
package com.lvmama.vst.comm.mybatis;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
/**
* sqlSession基类
*
* @author wenzhengtao
*
*/
public class SqlSessionTemplateDaoSupport {
protected SqlSessionTemplate sqlSession;
protected boolean externalSqlSession;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSession = sqlSessionTemplate;
this.externalSqlSession = true;
}
public final SqlSession getBatchSqlSession() {
return new SqlSessionTemplate(this.sqlSession.getSqlSessionFactory(), ExecutorType.BATCH);
}
public SqlSession getSqlSession() {
return this.sqlSession;
}
@Autowired(required = false)
public final void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
if (!this.externalSqlSession) {
this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
}
}
}
2.对mapp.xml中的可操作表进行封装
package com.lvmama.vst.comm.mybatis;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.RowBounds;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
/**
* MyBatis的Dao基类
*
* @author wenzhengtao
*/
@Repository
public class MyBatisDao extends SqlSessionTemplateDaoSupport {
private static final Log LOG = LogFactory.getLog(MyBatisDao.class);
private int maxRows = 1001;
private int maxRowsForReport = 50000;
private String namespaceName;
public MyBatisDao(String namespaceName) {
super();
this.namespaceName = namespaceName;
}
private String createStatementName(String id) {
return namespaceName + "." + id;
}
protected int insert(String key, Object object) {
if (object != null) {
return getSqlSession().insert(createStatementName(key), object);
}
return 0;
}
protected int update(String key, Object object) {
if (object != null) {
return getSqlSession().update(createStatementName(key), object);
}
return 0;
}
protected int delete(String key, Serializable id) {
if (id != null) {
return getSqlSession().delete(createStatementName(key), id);
}
return 0;
}
protected int delete(String key, Object object) {
if (object != null) {
return getSqlSession().delete(createStatementName(key), object);
}
return 0;
}
@SuppressWarnings({ "unchecked" })
protected <T> T get(String key, Object params) {
if (params != null) {
return (T) getSqlSession().selectOne(createStatementName(key), params);
} else {
return null;
}
}
/**
* 重载一个无参数的get方法,供vst_search使用
* @author wenzhengtao
* @param key
* @return
*/
@SuppressWarnings({ "unchecked" })
protected <T> T get(String key) {
return (T) getSqlSession().selectOne(createStatementName(key));
}
protected <T> List<T> getList(String key) {
return getSqlSession().selectList(createStatementName(key));
}
protected <T> List<T> getList(String key, Object params) {
if (params != null) {
return getSqlSession().selectList(createStatementName(key), params);
} else {
return null;
}
}
protected <T> List<T> queryForList(String statementName) throws DataAccessException {
return queryForList(statementName, null);
}
protected <T> List<T> queryForList(final String statementName, final Object parameterObject) throws DataAccessException {
if (parameterObject != null) {
List<T> result = getSqlSession().selectList(createStatementName(statementName), parameterObject, new RowBounds(0, maxRows));
if ((result != null) && (result.size() == maxRows)) {
LOG.warn("SQL Exception: result size is greater than the max rows, " + namespaceName + "." + statementName);
}
return result;
} else {
return null;
}
}
protected <T> List<T> queryForList(String statementName, int skipResults, int maxResults) throws DataAccessException {
if ((maxResults - skipResults) >= maxRows) {
maxResults = skipResults + maxRows;
LOG.warn("SQL Exception: result size is greater than the max rows, " + createStatementName(statementName));
}
return queryForList(statementName, null, skipResults, maxResults);
}
protected <T> List<T> queryForList(final String statementName, final Object parameterObject, final int skipResults, final int maxResults) throws DataAccessException {
int tempMaxResults = maxResults;
if ((maxResults - skipResults) >= maxRows) {
tempMaxResults = skipResults + maxRows;
LOG.warn("SQL Exception: result size is greater than the max rows, " + createStatementName(statementName));
}
return getSqlSession().selectList(createStatementName(statementName), parameterObject, new RowBounds(skipResults, tempMaxResults));
}
// 数据量比较大的报表导出请用这个接口
protected <T> List<T> queryForListForReport(String statementName) throws DataAccessException {
return queryForListForReport(statementName, null);
}
// 数据量比较大的报表导出请用这个接口
protected <T> List<T> queryForListForReport(final String statementName, final Object parameterObject) throws DataAccessException {
List<T> result = getSqlSession().selectList(createStatementName(statementName), parameterObject, new RowBounds(0, maxRowsForReport));
if ((result != null) && (result.size() == maxRowsForReport)) {
LOG.warn("SQL Exception: result size is greater than the max rows, " + statementName);
}
return result;
}
// 数据量比较大的报表导出请用这个接口
protected <T> List<T> queryForList(final String statementName, final Object parameterObject, final boolean isForReportExport) throws DataAccessException {
int maxRowsTemp = maxRows;
if (isForReportExport) {
maxRowsTemp = maxRowsForReport;
}
List<T> result = getSqlSession().selectList(createStatementName(statementName), parameterObject, new RowBounds(0, maxRowsTemp));
if ((result != null) && (result.size() == maxRowsTemp)) {
LOG.warn("SQL Exception: result size is greater than the max rows, " + statementName);
}
return result;
}
}
package com.lvmama.vst.comm.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.lvmama.vst.comm.mybatis.MyBatisDao;
import com.lvmama.vst.comm.po.ComFileMap;
@Repository
public class ComFileMapDAO extends MyBatisDao{
public ComFileMapDAO() {
super("COM_FILE_MAP");
}
public int deleteByPrimaryKey(Long comFileId) {
return super.delete("deleteByPrimaryKey", comFileId);
}
public int insert(ComFileMap record) {
return super.insert("insert", record);
}
public int insertSelective(ComFileMap record) {
return super.insert("insertSelective", record);
}
public ComFileMap selectByPrimaryKey(Long comFileId) {
return super.get("selectByPrimaryKey", comFileId);
}
public int updateByPrimaryKeySelective(ComFileMap record) {
return super.update("updateByPrimaryKeySelective", record);
}
public int updateByPrimaryKey(ComFileMap record) {
return super.update("updateByPrimaryKeySelective", record);
}
public List<ComFileMap> selectByParams(Map<String, Object> params) {
return super.queryForList("selectByParams", params);
}
public ComFileMap getByFileName(String fileName) {
Map<String, Object> params =new HashMap<String, Object>();
params.put("fileName", fileName);
return super.get("selectByParams", params);
}
public ComFileMap getByFileId(Long fileId) {
Map<String, Object> params =new HashMap<String, Object>();
params.put("fileId", fileId);
return super.get("selectByParams", params);
}
}
Spring配置样本
<!-- 数据源配置,使用应用内的DBCP数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<property name="maxActive">
<value>${jdbc.maxActive}</value>
</property>
<property name="maxWait">
<value>${jdbc.maxWait}</value>
</property>
<property name="maxIdle">
<value>${jdbc.maxIdle}</value>
</property>
<property name="initialSize">
<value>${jdbc.initSize}</value>
</property>
<property name="removeAbandoned">
<value>true</value>
</property>
<property name="testWhileIdle">
<value>true</value>
</property>
<property name="testOnBorrow">
<value>false</value>
</property>
<property name="validationQuery">
<value>SELECT 1 FROM SYS.DUAL</value>
</property>
</bean>
<!-- mysql数据源配置,使用应用内的DBCP数据库连接池 -->
<bean id="dataSourceMysql" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>${jdbc.mysql.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.mysql.url}</value>
</property>
<property name="username">
<value>${jdbc.mysql.username}</value>
</property>
<property name="password">
<value>${jdbc.mysql.password}</value>
</property>
<property name="maxActive">
<value>${jdbc.mysql.maxActive}</value>
</property>
<property name="maxWait">
<value>${jdbc.mysql.maxWait}</value>
</property>
<property name="maxIdle">
<value>${jdbc.mysql.maxIdle}</value>
</property>
<property name="initialSize">
<value>${jdbc.mysql.initSize}</value>
</property>
<property name="removeAbandoned">
<value>true</value>
</property>
</bean>
<!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:sqlmap-config.xml"/>
<property name="mapperLocations">
<value>classpath*:com/lvmama/vst/interfacePlatform/map/oracle/*.xml</value>
</property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!-- 连接事务的注解配置
<tx:annotation-driven transaction-manager="transactionManager"/>
-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="allManagerMethod" expression="execution(* com.lvmama..*.*ServiceImpl.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod"/>
</aop:config>