2011年9月23日星期五

How-to-bind-String-to-java.sql.Timestamp

http://forum.springsource.org/showthread.php?48979-How-to-bind-String-to-java.sql.Timestamp

 

java.sql.TimeStamp is derived from java.util.Date. It shouldn't be hard to figure out how to handle that in the persistence layer- in fact I'm willing to bet that some persistence tools can handle that conversion automatically.

In regard to your command object, however, you have a tougher problem using TimeStamp. I'll explain why.

As I noted, TimeStamp is derived from java.util.Date. Spring has an out-of-the-box CustomDateEditor property editor that does conversions from Strings (like on a form filled out by a user) to java.util.Date. It also converts from java.util.Date back to String when a BindingResult is being used to re-populate form fields because the submission failed validation.

Now, for the CustomDateEditor to take the Date it has converted your String to and "jam" it into a TimeStamp field is not possible because it requires an explicit downcast. Spring does no such thing on your behalf. In fact- off the top of my head, I don't think such a downcast is even legal in Java- meaning you'd get an exception.

Do you see why I'm recommending going back to java.util.Date? It's the standard class used for transporting date (and time) information.

If you're really gung-ho about sticking with java.sql.TimeStamp, however, your next best bet is to create your own CustomTimeStampEditor. Basically crack open and copy the code for Spring's CustomeDateEditor and then modify it to suit TimeStamp.

没有评论:

发表评论