|
IBatis通用DAO的封装
[color=#999999 !important]已有 521 次阅读[color=#999999 !important]2012-8-17 08:36 |[color=#999999 !important]个人分类:IBATIS| [color=#999999 !important]IBatis, Java, 淘课江湖, 封装
IBatis一个基于Java的数据持久层框架, 是一种“半自动化”的ORM实现,ibatis 并不会为程序员在运行期自动生成 SQL 执行。具体的 SQL 需要程序员编写,然后通过映射配置文件,将SQL所需的参数,以及返回的结果字段映射到指定 POJO。
很多情况下在与java集成的过程中,一般会使用底层的数据操作接口来实现一些SQL操作,如在具体模块的DAO实现层:
@Resource(name = "sqlMapClient")
private SqlMapClient sqlMapClient;//配置文件中加载后使用注解的方式获取数据库操作接口
public Goods queryGoods(Map parameMap)
throws SQLException {
return (Goods)sqlMapClient.queryForObject("goodsSQLMap.queryGoodsDiscuss",parameMap);//此方法中的参数均与配置文件中对应
}
以上是最直接的调用方法,简单明了,当然你也可以将其封装成通用的DAO,不用直接面对底层,封装如下(仅供参考):
/**
* IBatis Dao的泛型基类,使用泛型后有比较好的通用性
* 继承于Spring的SqlMapClientDaoSupport,提供分页函数和若干便捷查询方法,并对返回值作了泛型类型转换.
*/
@SuppressWarnings("unchecked")
public class IBatisGenericDao extends SqlMapClientDaoSupport {
public static final String POSTFIX_INSERT = ".insert";
public static final String POSTFIX_UPDATE = ".update";
public static final String POSTFIX_DELETE = ".delete";
public static final String POSTFIX_DELETE_PRIAMARYKEY = ".deleteByPrimaryKey";
public static final String POSTFIX_SELECT = ".select";
public static final String POSTFIX_SELECTMAP = ".selectByMap";
public static final String POSTFIX_SELECTSQL = ".selectBySql";
public static final String POSTFIX_COUNT = ".count";
/**
* 根据ID获取对象
*
* @throws BaseException
* @throws SQLException
*/
public <T> T get(Class<T> entityClass, Serializable id) throws BaseException, SQLException {
T o = (T) getSqlMapClient().queryForObject(entityClass.getName() + POSTFIX_SELECT, id);
if (o == null)
throw new BaseException(BaseException.DATA_NOTFOUND, "未找到实体: " + id);
return o;
}
/**
* 获取全部对象
* @throws SQLException
*/
public <T> List<T> getAll(Class<T> entityClass) throws SQLException {
return getSqlMapClient().queryForList(entityClass.getName() + POSTFIX_SELECT, null);
}
/**
* 新增对象
* @throws SQLException
*/
public void insert(Object o) throws SQLException {
getSqlMapClient().insert(o.getClass().getName() + POSTFIX_INSERT, o);
}
/**
* 保存对象
* @throws SQLException
*/
public int update(Object o) throws SQLException {
return getSqlMapClient().update(o.getClass().getName() + POSTFIX_UPDATE, o);
}
/**
* 删除对象
* @throws SQLException
*/
public int remove(Object o) throws SQLException {
return getSqlMapClient().delete(o.getClass().getName() + POSTFIX_DELETE, o);
}
/**
* 根据ID删除对象
* @throws SQLException
*/
public <T> int removeById(Class<T> entityClass, Serializable id) throws SQLException {
return getSqlMapClient().delete(entityClass.getName() + POSTFIX_DELETE_PRIAMARYKEY, id);
}
/**
* map查询.
*
* @param map
* 包含各种属性的查询
* @throws SQLException
*/
public <T> List<T> find(Class<T> entityClass, Map<String, Object> map) throws SQLException {
if (map == null)
return this.getSqlMapClient().queryForList(entityClass.getName() + POSTFIX_SELECT, null);
else {
map.put("findBy", "True");
return this.getSqlMapClient()
.queryForList(entityClass.getName() + POSTFIX_SELECTMAP, map);
}
}
/**
* sql 查询.
*
* @param sql
* 直接sql的语句(需要防止注入式攻击)
* @throws SQLException
*/
public <T> List<T> find(Class<T> entityClass, String sql) throws SQLException {
Assert.hasText(sql);
if (StringUtils.isEmpty(sql))
return this.getSqlMapClient().queryForList(entityClass.getName() + POSTFIX_SELECT, null);
else
return this.getSqlMapClient()
.queryForList(entityClass.getName() + POSTFIX_SELECTSQL, sql);
}
/**
* 根据属性名和属性值查询对象.
*
* @return 符合条件的对象列表
* @throws SQLException
*/
public <T> List<T> findBy(Class<T> entityClass, String name, Object value) throws SQLException {
Assert.hasText(name);
Map<String, Object> map = new HashMap<String, Object>();
map.put(name, value);
return find(entityClass, map);
}
/**
* 根据属性名和属性值查询对象.
*
* @return 符合条件的唯一对象
*/
public <T> T findUniqueBy(Class<T> entityClass, String name, Object value) {
Assert.hasText(name);
Map<String, Object> map = new HashMap<String, Object>();
try {
PropertyUtils.getProperty(entityClass.newInstance(), name);
map.put(name, value);
map.put("findUniqueBy", "True");
return (T) getSqlMapClient().queryForObject(entityClass.getName() + POSTFIX_SELECTMAP,
map);
} catch (Exception e) {
logger.error("Error when propertie on entity," + e.getMessage(), e.getCause());
return null;
}
}
/**
* 根据属性名和属性值以Like AnyWhere方式查询对象.
* @throws SQLException
*/
public <T> List<T> findByLike(Class<T> entityClass, String name, String value) throws SQLException {
Assert.hasText(name);
Map<String, Object> map = new HashMap<String, Object>();
map.put(name, value);
map.put("findLikeBy", "True");
return getSqlMapClient().queryForList(entityClass.getName() + POSTFIX_SELECTMAP, map);
}
/**
* 判断对象某些属性的值在数据库中不存在重复
*
* @param tableName
* 数据表名字
* @param names
* 在POJO里不能重复的属性列表,以逗号分割 如"name,loginid,password" <br>
* FIXME how about in different schema?
*/
public boolean isNotUnique(Object entity, String tableName, String names) {
try {
String primarykey;
Connection con = getSqlMapClient().getCurrentConnection();
ResultSet dbMetaData = con.getMetaData().getPrimaryKeys(con.getCatalog(), null, tableName);
dbMetaData.next();
if (dbMetaData.getRow() > 0) {
primarykey = dbMetaData.getString(4);
if (names.indexOf(primarykey) > -1)
return false;
} else {
return true;
}
} catch (SQLException e) {
logger.error(e.getMessage(), e);
return false;
}
return false;
}
/**
* 分页查询函数,使用PaginatedList.
*
* @param pageNo
* 页号,从0开始.
* @throws SQLException
*/
@SuppressWarnings("rawtypes")
public DataPage pagedQuery(String sqlName, HashMap<String, Object> hashMap, Integer pageNo, Integer pageSize)
throws SQLException {
if (pageNo == null || pageSize == null) {
List list = getSqlMapClient().queryForList(sqlName, hashMap);
if (list == null || list.size() == 0) {
return new DataPage();
} else {
return new DataPage(0, list.size(), list.size(), list);
}
} else {
Assert.hasText(sqlName);
Assert.isTrue(pageNo >= 1, "pageNo should start from 1");
// Count查询
Integer totalCount = (Integer) getSqlMapClient().queryForObject(sqlName + ".Count", hashMap);
if (totalCount < 1) {
return new DataPage();
}
// 实际查询返回分页对象
int startIndex = DataPage.getStartOfPage(pageNo, pageSize);
hashMap.put("startIndex", startIndex);
hashMap.put("pageSize", pageSize);
List list = getSqlMapClient().queryForList(sqlName, hashMap);
return new DataPage(startIndex, totalCount, pageSize, list);
}
}
public String getMappedSQL(String sqlName) {
String sql = null;
SqlMapClientImpl sqlmap = (SqlMapClientImpl) getSqlMapClient();
MappedStatement stmt = sqlmap.getMappedStatement(sqlName);
StaticSql staticSql = (StaticSql) stmt.getSql();
sql = staticSql.getSql(null, null);
return sql;
}
}
以上两种方式可根据项目的需求自由选择,但是需要注意的是,无论是哪种方式,都要将配置文件和dao具体实现中所需参数保持一致 |
|