SimpleDAO 给予spring jdbc tamplate 的dao 实现。运行于jdk6.0之上。
在自己开发中觉得试用ibatis,hibernate总是有这里那里不如意的地方。 ibatis实现动态条件查询不方便。hibernate试用起来感觉很笨重,学习曲线陡。 所以在一些小项目中自己总结开发了这一工具包。也就是一 DAO。 试用该DAO能够方便的实现单表的增删查改功能。实现复杂的查询跟新可能将SQL写到独立的文件里面。
以下是本DAO接口
SimpleDAO.java:
实现:
使用举例,加粗部分为DAO使用代码:
在此推荐一下:
饰装修评价推荐查询网
http://www.zhuangxiu007.com
在自己开发中觉得试用ibatis,hibernate总是有这里那里不如意的地方。 ibatis实现动态条件查询不方便。hibernate试用起来感觉很笨重,学习曲线陡。 所以在一些小项目中自己总结开发了这一工具包。也就是一 DAO。 试用该DAO能够方便的实现单表的增删查改功能。实现复杂的查询跟新可能将SQL写到独立的文件里面。
以下是本DAO接口
SimpleDAO.java:
- package cn.kkp.dao;
- import java.util.List;
- import cn.kkp.dao.query.BoolExpr;
- import cn.kkp.dao.query.Insert;
- import cn.kkp.dao.query.Select;
- import cn.kkp.dao.query.Update;
- public interface SimpleDAO<T>
- {
- public int delete(BoolExpr condition);
- public T create(T obj);
- public T create(Insert<T> insert);
- public T create(T obj, String... insertedAttrs);
- public int modify(Update<T> update);
- public int modify(T obj, BoolExpr condition);
- public int modify(T obj, BoolExpr condition, String... updatedAttrs);
- public int modify(String statementId, Object... parameters);
- public T query(Select<T> select);
- public T query(BoolExpr condition);
- public T query(BoolExpr condition, String... selectedAttrs);
- public T query(String statementId, Object... parameters);
- public List<T> queryList();
- public List<T> queryList(Select<T> select);
- public List<T> queryList(BoolExpr condition);
- public List<T> queryList(BoolExpr condition, String... selectedAttrs);
- public List<T> queryList(String statementId, Object... parameters);
- }
- package cn.kkp.dao.springjdbc;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.log4j.Logger;
- import org.springframework.dao.DataAccessException;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.core.ResultSetExtractor;
- import cn.kkp.dao.SimpleDAO;
- import cn.kkp.dao.query.BoolExpr;
- import cn.kkp.dao.query.Delete;
- import cn.kkp.dao.query.Insert;
- import cn.kkp.dao.query.MySQLTranslator;
- import cn.kkp.dao.query.OQLObject;
- import cn.kkp.dao.query.Translator;
- import cn.kkp.dao.query.Select;
- import cn.kkp.dao.query.Update;
- import cn.kkp.dao.query.Where;
- import cn.kkp.util.BeanUtil;
- import cn.kkp.util.DBUtil;
- import cn.kkp.util.FileUtil;
- import cn.kkp.util.StringUtil;
- public class SimpleDAOImpl<T> extends JdbcTemplate
- implements SimpleDAO<T>
- {
- public SimpleDAOImpl() {
- init();
- }
- @SuppressWarnings("unchecked")
- public SimpleDAOImpl(String typeClassName) throws ClassNotFoundException {
- init();
- this.typeClass = (Class<T>) getClass().getClassLoader().loadClass(typeClassName);
- }
- @SuppressWarnings("unchecked")
- public SimpleDAOImpl(Class<T> typeClass){
- init();
- this.typeClass = typeClass;
- }
- private void init(){
- logger = Logger.getLogger(SimpleDAOImpl.class);
- sqlCache = new HashMap<String, String>();
- }
- @Override
- public int delete(BoolExpr condition) {
- Delete<T> delete = new Delete<T>(typeClass, new Where(condition));
- return super.update(translator.toSQL(delete.exportOQL()), delete.exportParamters());
- }
- @SuppressWarnings("unchecked")
- @Override
- public List<T> queryList(final Select<T> select) {
- return (List<T>) super.query(translator.toSQL(select.exportOQL()), select.exportParamters(), new ResultSetExtractor() {
- public Object extractData(ResultSet rs) throws SQLException,
- DataAccessException {
- String attrs[] = select.getSelectedAttrs();
- String cols[] = new String[attrs.length];
- for (int i = 0, len = attrs.length; i < len; i++) {
- cols[i] = translator.toSQL(attrs[i]);
- }
- return SimpleDAOImpl.this.extractData1(rs, typeClass, cols, attrs);
- }
- });
- }
- @SuppressWarnings("unchecked")
- @Override
- public List<T> queryList(BoolExpr condition, String... selectedAttrs) {
- return queryList(new Select<T>(typeClass, new Where(condition), selectedAttrs));
- }
- @Override
- public List<T> queryList() {
- return queryList((BoolExpr)null);
- }
- private List<T> extractData1(ResultSet rs, Class<T> type, String []cols, String [] attrs) throws SQLException {
- List<T> list = new ArrayList<T>();
- for (T ret; rs.next(); list.add(ret)) {
- ret = BeanUtil.newBean(type);
- for (int i = 0; i < cols.length; i++) {
- String columnName = cols[i];
- String attrName = attrs != null ? attrs[i] : columnName;
- Class<?> attrType = BeanUtil.getAttrType(type, attrName);
- BeanUtil.setAttr(ret, attrName, DBUtil.getValue(rs, columnName, attrType));
- }
- }
- return list;
- }
- public Class<T> getTypeClass() {
- return typeClass;
- }
- public void setTypeClass(Class<T> typeClass) {
- this.typeClass = typeClass;
- }
- @Override
- public T create(T obj) {
- return create(new Insert<T>(obj));
- }
- @Override
- public T create(Insert<T> insert) {
- super.update(translator.toSQL(insert.exportOQL()), insert.exportParamters());
- return insert.getInsertedBean();
- }
- @Override
- public T create(T obj, String... insertedAttrs) {
- return create(new Insert<T>(obj, insertedAttrs));
- }
- @Override
- public T query(BoolExpr condition) {
- return query(new Select<T>(typeClass, new Where(condition)));
- }
- @Override
- public T query(BoolExpr condition, String... selectedAttrs) {
- List<T> list = queryList(condition, selectedAttrs);
- return list.size() != 0 ? list.get(0) : null;
- }
- @Override
- public T query(Select<T> select) {
- List<T> list = queryList(select);
- return list.size() != 0 ? list.get(0) : null;
- }
- @Override
- public T query(String statmentId, Object... parameters) {
- List<T> reuslt = queryList(statmentId, parameters);
- return reuslt.size() != 0 ? reuslt.get(0) : null;
- }
- @Override
- public List<T> queryList(BoolExpr condition) {
- Select<T> select = new Select<T>(typeClass);
- if(condition!=null)
- select.setWhere(new Where(condition));
- return queryList(select);
- }
- @SuppressWarnings("unchecked")
- @Override
- public List<T> queryList(String statmentId, Object... parameters) {
- String sql = getSQL(statmentId);
- Object [] sqlAndParams = expandSQL(sql, parameters);
- return (ArrayList<T>) super.query((String)sqlAndParams[0] , (Object[])sqlAndParams[1], new ResultSetExtractor() {
- public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
- String [] columns = DBUtil.getColumnNames(rs);
- String [] attrs = new String[columns.length];
- for (int i = 0, len = columns.length; i < len; i++) {
- attrs[i] = translator.toOQL(columns[i]);
- }
- return SimpleDAOImpl.this.extractData1(rs, typeClass, columns, attrs);
- }
- });
- }
- @Override
- public int modify(Update<T> update) {
- return super.update(translator.toSQL(update.exportOQL()), update.exportParamters());
- }
- @Override
- public int modify(T obj, BoolExpr condition) {
- return this.modify(new Update<T>(obj, new Where(condition)));
- }
- @Override
- public int modify(T obj, BoolExpr condition, String... updatedAttrs) {
- return this.modify(new Update<T>(obj, new Where(condition), updatedAttrs));
- }
- @Override
- public int modify(String statmentId, Object... parameters) {
- String sql = getSQL(statmentId);
- Object [] sqlAndParams = expandSQL(sql, parameters);
- return super.update((String)sqlAndParams[0], (Object[])sqlAndParams[1]);
- }
- private String getSQL(String statementId) {
- String sql = (String) sqlCache.get(statementId);
- if (sql == null) {
- sql = readSQL(statementId);
- sqlCache.put(statementId, sql);
- }
- return sql;
- }
- private String readSQL(String statementId) {
- return sqlFileDir.startsWith("classpath:")?
- StringUtil.getText(getClass().getResourceAsStream(sqlFileDir.substring(10)+statementId+".sql")):
- FileUtil.getTextFromFile(sqlFileDir+statementId+".sql");
- }
- /**
- * if paramters contain OQLObject object, the function will expand it
- * @param orignalSQL
- * @param parameters
- * @return
- */
- private Object [] expandSQL(String orignalSQL, Object [] parameters){
- StringBuilder sb = new StringBuilder();
- List<Object> newParams = new ArrayList<Object>();
- int count = 0;
- for(int i=0, len = orignalSQL.length(); i<len; i++){
- char ch = orignalSQL.charAt(i);
- if(ch == '?'){
- if(parameters[count] instanceof OQLObject){
- OQLObject oqlObject = (OQLObject)parameters[count++];
- String expandSQL = translator.toSQL(oqlObject.exportOQL());
- sb.append(expandSQL);
- Collections.addAll(newParams, oqlObject.exportParamters());
- continue;
- }
- newParams.add(parameters[count++]);
- }
- sb.append(ch);
- }
- return new Object[]{sb.toString(), newParams.toArray(new Object[newParams.size()])};
- }
- public String getSqlFileDir() {
- return sqlFileDir;
- }
- public void setSqlFileDir(String sqlFileDir) {
- this.sqlFileDir = sqlFileDir;
- }
- public Translator getTranslator() {
- return translator;
- }
- public void setTranslator(Translator translator) {
- this.translator = translator;
- }
- protected Logger logger;
- private Map<String, String> sqlCache;
- private String sqlFileDir;
- private Class<T> typeClass;
- private Translator translator = new MySQLTranslator();
- }
- public class SecurityManagerImpl extends ManagerSupport implements SecurityManager {
- @Override
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException, DataAccessException {
- SimpleDAO<UserInfor> userDAO = getSimpleDAO(UserInfor.class);
- UserInfor userInfor = userDAO.query(new BoolExpr("username=?", username));
- if (userInfor == null)
- throw new UsernameNotFoundException("User not found");
- SimpleDAO<UserRole> roleDAO = getSimpleDAO(UserRole.class);
- List<UserRole> roles = roleDAO.queryList("get_role_by_username", username);
- UserDetail ud = new UserDetail(userInfor);
- ud.setAuthority(GrantedAuthority.convertFromString(roles.toArray(new String[roles.size()])));
- return ud;
- }
- }