数据库Java字段猜测
我正在开发一个从数据库中提取数据的小型Java库
假设有一个通用Java类:
公共类MyClass{
public int valueA;
public String valueB;
public Double valueC;
//getter and setter methods.
}
然后定义一个SQL查询字符串,得到泛型类MyClass
的类
String sql = "Select c.valueA, c.valueB, c.valueC from my_table c";
Class<MyClass> type = MyClass.class;
List<MyClass> results = extractData(sql, type)M
其中extractData
方法类似于以下方法:
public<T> List<T> extractData(String sql, Class<T> type){
//1)Do everything that is necessary to retrieve a ResultSet by the sql String.
//2)Then, for each row in the ResultSet
//2.1)Create a new instance of object of type T.
//2.2)Automatically matches the field name from the query
// with the field name of the specified class.
//2.3) add the object to the list to be returned.
//3) return the list of results of type T.
}
在实践中,如果可能,我如何实施步骤2.2强>
我想这是可能的,因为我在PHP框架中使用了这种方法
# 1 楼答案
您几乎肯定希望在这里使用第三方ORM映射器
Check out this list of frameworks on Wikipedia
另外,请阅读这篇文章,因为这是最好的两篇文章,答案也很好:Hibernate Vs iBATIS
# 2 楼答案
您需要的是结果集元数据(获取列的名称),以及反射来分析类并设置字段。期望在这两者之间编写大量的粘合代码(例如,从类的字段类型中,您需要猜测每个列使用哪个getXXX()/datatype)
这并不太复杂,但需要一些思考。有许多潜在的边缘情况(例如继承)以及如何处理隐式类型转换(当类字段和列数据类型不直接兼容时)