Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

jdbc - java.lang.ClassCastException: oracle.sql.TIMESTAMP cannot be cast to java.sql.Timestamp

I am working on an application that streams ResultSet over a network. I ended up using a CachedRowSetImpl class. But when I connect to an Oracle DB, I get an error like this

java.lang.ClassCastException: oracle.sql.TIMESTAMP cannot be cast to java.sql.Timestamp

Please help.

The source code is as follows:

ResultSet res = response.getResultSet(); //resultset from the server
while (res.next()) {
    Agent agent = new Agent();
    agent.setName(res.getString(2));
    agent.setMobile(res.getString(1));
    agent.setBalance(res.getLong(4));
    agent.setLastUpdate(res.getDate(3)); //date from the result set
    agent.setAccountNumber(res.getString(5));
}

The error ...

java.lang.ClassCastException: oracle.sql.TIMESTAMP cannot be cast to java.sql.Timestamp java.lang.ClassCastException: oracle.sql.TIMESTAMP cannot be cast to java.sql.Timestamp at com.sun.rowset.CachedRowSetImpl.getDate(CachedRowSetImpl.java:2139)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The javadoc for ResultSet.getObject() mandates that the JDBC type should be mapped to a Java type as prescribed by the JDBC spec (TIMESTAMP -> java.sqlTimestmp):

This method will return the value of the given column as a Java object. The type of the Java object will be the default Java object type corresponding to the column's SQL type, following the mapping for built-in types specified in the JDBC specification.

As you have noticed, the Oracle driver is by default not compliant with the standard and uses oracle.sql.TIMESTAMP instead (which does not extend java.sql.Timestamp). The good news is that you can force JDBC compliance by setting the oracle.jdbc.J2EE13Compliant system property to true during vm startup:

java -Doracle.jdbc.J2EE13Compliant=true YourApplication

or programmatically

System.getProperties().setProperty("oracle.jdbc.J2EE13Compliant", "true")

Once you do this, getResult() will return instances of java.sql.Timestamp, as expected.

For more details see the relevant section from the Oracle JDBC Driver Documentation, which describes several ways of setting oracle.jdbc.J2EE13Compliant.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...