您的位置:首页 > 其它

DAO,如何实现模糊查询

2016-03-14 14:42 459 查看
定义一个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{

@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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: