DAO,如何实现模糊查询

来源:互联网 发布:知乎a tender feeling 编辑:程序博客网 时间:2024/06/06 05:00

定义一个DAO

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{@Overridepublic 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());}@Overridepublic List<Customer> getAll() {String sql  = "SELECT id,name,address,phone FROM customerss";return getForList(sql);}}


1 0
原创粉丝点击