MyBatis学习笔记-Spring集成DAO层实现方式记录

Spring MyBatis 版本如下:
spring                  4.2.6.RELEASE
mybatis                3.4.0
mybatis-spring    1.3.0

Spring集成MyBatis的DAO层两种实现方式如下

第一种基于传统DAO层接口实现类方式:
public interface IUserDAO extends IGenericDAO {

}

@Repository("userDAO")
public class UserDAOImpl extends GenericDAOImpl implements IUserDAO {

}

@Repository("genericDAO")
public class GenericDAOImpl
	extends SqlSessionDaoSupport implements IGenericDAO {

	@Resource(name = "sqlSessionTemplate")
	protected SqlSessionTemplate sqlSessionTemplate = null;

	public static final String INSERT = "insert";
	public static final String INSERT_BATCH = "insertBatch";
    	public static final String UPDATE = "update";
    	public static final String UPDATE_BATCH = "updateBatch";
    	public static final String DELETE_BY_PK = "deleteByPK";
    	public static final String READ_DATA_BY_PK = "readDataByPK";
    	public static final String READ_DATA_BY_CONDITION = "readDataByCondition";
    	public static final String READ_DATA_LIST_BY_CONDITION = "readDataListByCondition";
    	public static final String READ_DATA_PAGINATION_BY_CONDITION = "readDataPaginationByCondition";
    	public static final String READ_COUNT_BY_CONDITION = "readCountByCondition";

	
	private Class entityClass = null;

	@SuppressWarnings("unchecked")
	public GenericDAOImpl() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            entityClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
        }
	}
	
	@Override
	@Resource(name = "sqlSessionTemplate")
	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		super.setSqlSessionTemplate(sqlSessionTemplate);
	}
	
	protected SqlSession sqlSession() {
		return sqlSessionTemplate.getSqlSessionFactory().openSession();
	}
	
	protected void closeSession(SqlSession sqlSession) {
		if (null != sqlSession) sqlSession.close();
	}
	
	protected SqlSession batchSqlSession() {
		return sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH);
	}

	protected String obtainSQLID(String sqlId) {
		Configuration configuration = sqlSessionTemplate.getConfiguration();
		String dialect = "mysql";
		if (null != configuration.getVariables()) {
			dialect = configuration.getVariables().getProperty("dialect");
		}
		StringBuffer sb = new StringBuffer();
		sb.append(dialect).append(".").append(entityClass.getName()).append(".").append(sqlId);
		return sb.toString();
	}

	@Override
	public void insert(Entity entity) {
		sqlSessionTemplate.insert(obtainSQLID(INSERT), entity);
	}
	
	@Override
	public void insert(List entities) throws DataException {
		SqlSession sqlSession = batchSqlSession();
		for (int i = 0, len = entities.size(); i < len; i++) {
			sqlSession.insert(obtainSQLID(INSERT), entities.get(i));
		}
		sqlSession.flushStatements();
		closeSession(sqlSession);
	}

	@Override
	public void update(Entity entity) {
		sqlSessionTemplate.update(obtainSQLID(UPDATE), entity);
	}

	@Override
	public void update(List entities) throws DataException {
		SqlSession sqlSession = batchSqlSession();
		for (int i = 0, len = entities.size(); i < len; i++) {
			sqlSession.update(obtainSQLID(UPDATE), entities.get(i));
		}
		sqlSession.flushStatements();
		closeSession(sqlSession);
	}
	
	@Override
	public void delete(Entity entity) throws DataException {
		
	}

	@Override
	public void deleteByPK(PK primaryKey) {
		sqlSessionTemplate.delete(obtainSQLID(DELETE_BY_PK), primaryKey);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Entity readDataByPK(PK pk) {
		return (Entity) sqlSessionTemplate.selectOne(obtainSQLID(READ_DATA_BY_PK), pk);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Entity readDataByCondition(Query query) {
		Map map = query.getCondition();
		return (Entity) sqlSessionTemplate.selectOne(obtainSQLID(READ_DATA_BY_CONDITION), map);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List readDataListByCondition(Query query) throws DataException {
		Map map = query.getCondition();
		List resultList = (List) sqlSessionTemplate.selectList(
				obtainSQLID(READ_DATA_LIST_BY_CONDITION), map);
		List entities = new ArrayList();
		for (int i = 0, len = resultList.size(); i < len; i++) {
			entities.add((Entity) resultList.get(i));
		}
		return entities;
	}

	@SuppressWarnings("unchecked")
	@Override
	public QueryResult readDataPaginationByCondition(Query query) throws DataException {
		Map map = query.getCondition();
		List resultList = (List) sqlSessionTemplate.selectList(
				obtainSQLID(READ_DATA_PAGINATION_BY_CONDITION), map);
		List entities = new ArrayList();
		for (int i = 0, len = resultList.size(); i < len; i++) {
			entities.add((Entity) resultList.get(i));
		}
		int totalRowNum = (Integer) map.get(Query.TOTAL_ROW_NUM);
		return new QueryResult(totalRowNum, entities);
	}
	
	@Override
	public Long readCountByCondition(Query query) throws DataException {
		Map map = query.getCondition();
		return  (Long) sqlSessionTemplate.selectOne(obtainSQLID(READ_COUNT_BY_CONDITION), map);
	}

	@Override
	public void flush() throws DataException {
		sqlSessionTemplate.clearCache();
	}
	
} 
  
这里需要注意的是 mybatis-spring 1.1.0或是之前版本,可以不用以下代码
@Override
@Resource(name = "sqlSessionTemplate")
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
	super.setSqlSessionTemplate(sqlSessionTemplate);
}


	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
 
	

	
	
	
	

	

       

typeAliasesPackage的多个选项可以用逗号分隔


传统DAO层的这种实现方式需要指定对应的SQLID。


第二种基于Mapper接口的动态代理方式:

@Repository("userMapper")
public interface UserMapper extends GenericMapper {

}

public interface GenericMapper  {

	public void insert(Entity entity) throws DataException;
	
	public void insert(List entities) throws DataException;

	public void update(Entity entity) throws DataException;
	
	public void update(List entities) throws DataException;

	public void delete(Entity entity) throws DataException;

	public void deleteByPK(PK pk) throws DataException;

	public Entity readDataByPK(PK pk) throws DataException;

	public Entity readDataByCondition(Query query) throws DataException;
	
	public List readDataListByCondition(Query query) throws DataException;

	public QueryResult readDataPaginationByCondition(Query query) throws DataException;
	
	public Long readCountByCondition(Query query) throws DataException;

	public void flush() throws DataException;
	
}


	  
	  


Mappper代理的这种实现方式不需要指定对应的SQLID,接口类里面的方法名字即对应的SQLID,namespace需要指定到对应的Mapper接口。 这里需要注意的是MapperScannerConfigurer的配置,可能会遇到无法加载DataSource相关属性的异常,这时候需要配置MapperScannerConfigurer的sqlSessionFactoryBeanName属性,并且检查下有没有配置default-autowire="byName",有的话去掉。



你可能感兴趣的:(J2EE,Spring,MyBatis,DAO)