DAO,如何实现模糊查询
2016-03-14 14:42
459 查看
定义一个DAO
定义一个接口CustomerDAO
定义一个类
定义一个继承了DAO 且实现了CustomerDAO 的类
public class DAO<T> { private QueryRunner queryRunner = new QueryRunner(); private Class<T> clazz; public DAO(){ Type superClass = getClass().getGenericSuperclass(); if(superClass instanceof ParameterizedType){ ParameterizedType parameterizedType = (ParameterizedType) superClass; Type[] typeArgs = parameterizedType.getActualTypeArguments(); if(typeArgs != null && typeArgs.length>0){ if(typeArgs[0] instanceof Class){ clazz = (Class<T>) typeArgs[0]; } } } } /** * 查询T 对应的List * 返回对应的T 所对应的List * @param sql * @param args * @return */ public List<T> getForList(String sql,Object...args){ Connection connection = null; try { connection = JdbcUtils.getConnection(); return queryRunner.query(connection, sql, new BeanListHandler<T>(clazz), args); } catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtils.releaseConnection(connection); } return null; } }
定义一个接口CustomerDAO
public interface CustomerDAO { public List<Customer> getForListWithCCustomer(CCustomer cc); /** * 返回一个list * @return */ public List<Customer> getAll(); }
定义一个类
public class CCustomer { private String name; private String address; private String phone; public CCustomer(String name, String address, String phone) { super(); this.name = name; this.address = address; this.phone = phone; } public String getName() { //实现 名字 的模糊查询 if(name == null){ name ="%%"; }else{ name ="%"+ name +"%"; } return name; } public void setName(String name) { this.name = name; } public String getAddress() { //实现 地址 的模糊查 if(address == null){ address ="%%"; }else{ address ="%"+ address +"%"; } return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { //实现 电话号码 的模糊查 if(phone == null){ phone ="%%"; }else{ phone ="%"+ phone +"%"; } return phone; } public void setPhone(String phone) { this.phone = phone; } }
定义一个继承了DAO 且实现了CustomerDAO 的类
public class CustomerDAOJdbcImpl extends DAO<Customer> implements CustomerDAO{ @Override public List<Customer> getForListWithCCustomer(CCustomer cc) { String sql = "SELECT id,name,address,phone FROM customerss " + "WHERE name LIKE ? AND address LIKE ? AND phone LIKE ?"; return getForList(sql,cc.getName(),cc.getAddress(),cc.getPhone()); } @Override public List<Customer> getAll() { String sql = "SELECT id,name,address,phone FROM customerss"; return getForList(sql); } }
相关文章推荐
- LVS集群的体系结构
- 13 Roman to Integer
- Linux基础回顾之基础命令三
- linux下启动tomcat
- 设计模式之访问者模式
- 几种上传文件组件的性能比较
- 【2016年Esri开发者大会亮点解析】Insights for ArcGIS,Apps家族再添重量级新丁
- iOS中音频
- Software Design Tools for Agile Teams, with UML, BPMN and More
- boostrap-非常好用但是容易让人忽略的地方------row
- 提高SQL查询效率的30种方法
- 各种排序复杂度
- centos系统使用命令查询版本信息
- Android之Adapter结构
- 支付介绍
- Nginx反向代理设置总结
- 关于UITableView
- java 死锁产生原因及解锁
- DB理论--mysql基础
- 【2016年Esri开发者大会亮点解析】Geo Analytics,给力的Big Data分析工具