应用场景:当返回的结果不确定时用泛型,然后具体的处理到底是返回bean还是list,由传入的具体实现类来决定。
(1)、比如
public class Test {
public static void main(String[] args) {
String sql = "SELECT * FROM t_user where id = ? and name = ? and phone = ?";
queryEntityList(User.class, sql, "1", "小明", "15465465");
}
/**
* 查询list
* @param entityClass: Class<T>在实例化的时候,T要替换成具体类
* @param sql SELECT * FROM t_user where id = ? and name = ? and phone = ?
* @param params params代表一个Object数组(Object[3])。
* 拼接sql后== SELECT * FROM t_user where id = '1' and name = '小明' and phone = '15465465'
* @return
*/
public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
List<T> entityList;
try {
entityList = query(sql, new BeanListHandler<T>(entityClass), params);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return entityList;
}
/**
* 泛型决定了返回类型
* 接口决定入参,决定了传入的是哪个具体实现类,调用的就是哪个具体实现类的方法。
*/
/**
*
* @param sql
* @param rsh 传入ResultSetHandler接口的具体实现类
* @param params
* @return
* @throws SQLException
*/
@SuppressWarnings("unused")
public static <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
throws SQLException {
T result = null;
/**
* 结果集ResultSet:可以根据
* while(rs.next()){
* int id=rs.getInt("id");
* }
* 来得到数据
*/
ResultSet rs = null;
//把数据库中的值封装到泛型中:T为什么对象则自动组装成什么对象
result = rsh.handle(rs);
return result;
}
}
-------------------------------------------------------------------------------------------------------------
/**
* 接口的具体实现类BeanList
* @author Administrator
*
* @param <T>
*/
public class BeanListHandler<T> implements ResultSetHandler<List<T>> {
private final Class<T> type;
private final RowProcessor convert;
public BeanListHandler(Class<T> type) {
this(type, ArrayHandler.ROW_PROCESSOR);
}
public BeanListHandler(Class<T> type, RowProcessor convert) {
this.type = type;
this.convert = convert;
}
/**
* 将数据结果集转换成bean,并返回
*/
public List<T> handle(ResultSet rs) throws SQLException {
List<T> list = new ArrayList<T>();
return list;
// return this.convert.toBeanList(rs, type);
}
}
-------------------------------------------------------------------------------------------------------------
/**
* 接口的具体实现类Bean
* @author Administrator
*
* @param <T>
*/
public class BeanHandler<T> implements ResultSetHandler<T> {
/**
* 由该处理程序生成的bean类.
*/
private final Class<T> type;
private final RowProcessor convert;
public BeanHandler(Class<T> type) {
this(type, ArrayHandler.ROW_PROCESSOR);
}
public BeanHandler(Class<T> type, RowProcessor convert) {
this.type = type;
this.convert = convert;
}
/**
* 将数据结果集转换成bean,并返回
*/
public T handle(ResultSet rs) throws SQLException {
T t = null;
try {
t = type.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
// return rs.next() ? this.convert.toBean(rs, this.type) : null;
}
}