This is a simple question: I know and have heard from almost everyone that using java.util.Date for anything in a Jdbc call is a bad idea. You should use either java.sql.Date or java.sql.Time or java.sql.Timestamp. However, what is the reason not to? I can’t find a good blog post or SO post explaining it, except that sometimes people see “weird behavior”.
Thanks!
EDIT:
So, I have seen this post. Yeah, the only part of that post that sort of answers my question is
…to most JDBC drivers which will happily devour it as if it was of
the correct type but when you request the data afterwards, you may
notice that you’re actually missing stuff.
However, that doesn’t really answer why.
Okay, so having read all the information throughout the answers, and the others posts pointed to in comments and so forth, I’ve decided to summarize what I learned:
The Setup:
From what I can see, there are three layers
The First Reason
Many JDBC class wrappers, such as Spring’s famous
SimpleJdbcTemplate, allowed you give it aMap<String, Object>as the argument map when executing a SQL statement. This is wonderfully simple, as it hands all the conversions from the objects to the properjava.sql.*types when it uses raw JDBC under the hood. The first problem is here: what happens if you have the following:What does Spring convert it to? A
java.sql.Date? Ajava.sql.Timestamp? Ajava.sql.Time? Or does it even cast it to ajava.lang.Object? As well explained by @BalusC in this answer to a different question and by another fellow here, there are big differences between those threejava.sqltypes. So, that’s the first reason not to usejava.util.Date: you can’t rely on the internal convention of a framework to handle the conversion for you.The Second Reason
Now, talking about raw JDBC calls, @The Nail explained that you need these
java.sqltypes to make JDBC calls, and he’s absolutely right, which was news to me. However, there is still the dreadedsetObjectcall. From reading the JavaDoc for that call, it seems a little ambiguous as to what it will do if give ajava.util.Date. So, the second reason not to use it is because of the ambiguity there.The Third Reason
Finally, talking about the level of the driver. I can attest with personal experience that sometimes Spring in conjunction with the Oracle driver does work with
java.util.Date. Sometimes. And then sometimes it doesn’t. So, because I have no clue how any particular version of any particular driver will handle ajava.util.Date, it’s best to be explicit. This is the third reason.Conclusion
In general, it looks like the reason is: “JDBC is not supposed to be used with
java.util.Date. If you do, you cannot be sure what will happen.” This is a good enough reason for me 🙂