DAO, 모호한 쿼리 구현 방법

DAO 정의
public class DAO {
	
	private QueryRunner queryRunner = new QueryRunner();
	
	private Class 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) typeArgs[0];
				}
			}
		}
	}
	
	
	/**
	 *   T    List 
	 *      T     List
	 * @param sql
	 * @param args
	 * @return
	 */
	public List getForList(String sql,Object...args){
		Connection connection = null;
		
		try {
			connection = JdbcUtils.getConnection();
			return queryRunner.query(connection, sql, new BeanListHandler(clazz), args);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			JdbcUtils.releaseConnection(connection);
		}
		
		return null;
	}
}

커넥터CustomerDAO 정의
public interface CustomerDAO {
	
	public List getForListWithCCustomer(CCustomer cc);
	
	/**
	 *     list
	 * @return
	 */
	public List 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 implements CustomerDAO{

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

좋은 웹페이지 즐겨찾기