问题描述
使用getObject方法从ResultSet对象检索列时,该类由JDBC驱动程序选择.我正在寻找一种选择在运行时检索列的类的方法.
When retrieving a column from a ResultSet object using the getObject method, the class is chosen by the JDBC driver. I am looking for a way to choose which class the column is retrieved as at runtime.
在下面的示例中,使用变量T作为整数创建类型Class1.
In the example below type Class1 is created with variable T as an Integer.
Class Class1<T>
{
public T getColumn(DataSource ds)
{
T value = null;
Connection con = null;
try
{
con = ds.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select 1 from dual");
rs.next();
Object o = rs.getObject(1); // I want an Integer but a BigDecimal is created!
value = (T) o; // ClassCastException here!
rs.close();
st.close();
}
finally
{
if (con != null) { con.close(); }
}
return i;
}
}
ResultSet类提供了一个名为getObject的方法,该方法接受列参数和Map类型的参数.映射类型仅用于UDT(用户定义类型).我还需要将此功能应用于基本SQL类型.我知道我可以使用switch/case语句来实现此目的的解决方案,但我正努力避免这种情况.这可能吗?
The ResultSet class provides a method called getObject that accepts a column argument and a type Map argument. This type Map is only used for UDT (user defined types). I need this functionality applied to basic SQL types as well. I know I can implement a solution to this using a switch/case statement but I'm trying to avoid that. Is this possible?
编辑
我应该提到我在Java 1.6上.看来这可能已在1.7中解决.感谢JB Nizet提供参考.
I should've mentioned I am on Java 1.6. It looks like this may have been solved in 1.7. Thanks JB Nizet for the reference.
推荐答案
JB Nizet提供了Java 1.7的答案: http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html #getObject-int-java.lang.Class-
JB Nizet has provided the answer for Java 1.7: http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html#getObject-int-java.lang.Class-
对于Java的早期版本,DolphinJava是正确的.我将不得不编写自己的代码.
For earlier versions of Java, DolphinJava is correct. I will have to write my own code.
我如何解决
使用上面的示例使用 Class1 ,我创建了扩展 Class1 的子类,其中T是所需的类型,然后制作了特定于类型的方法来调用getColumn Class1 中的方法:
Keeping with my example above using Class1, I created sub-classes that extend Class1 with T being the type needed and then made type-specific methods that call the getColumn method in Class1:
public Class1<T>
{
public Object getColumn(DataSource ds)
{
Object o = null;
Connection con = null;
try
{
con = ds.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select 1 from dual");
rs.next();
Object o = rs.getObject(1);
rs.close();
st.close();
}
finally
{
if (con != null) { con.close(); }
}
return o;
}
}
Class1Integer extends Class1<Integer>
{
public Integer getIntegerColumn()
{
Object o = getColumn(datasource);
Integer i = new Integer(o);
return i;
}
}
这篇关于是否可以将基本的JDBC SQL类型映射到Java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!