I have a Postgres DB, with a column named t_time
of type timestamp with time zone
.
When I use the psql
tool to see the contents of the column, I get, for example:
select t_time from table1 where ...
t_time
---------------------
2011-02-28 14:09:25
2011-02-28 14:09:23
This is the format I want.
However, when I run the same select query through my Java code, which uses Hibernate, I get the following:
2011-02-28 14:09:25.0
2011-02-28 14:09:23.0
As you can see, at the end a dot and a zero are added.
My question is - how do I specify the format I want to use?
Changing the query, for example like this,
select to_char(t_time, 'YYYY-MM-DD HH24:MI:ss') a开发者_运维问答s t_time from table1 where ...
is possible, but less desired since I have a few places in the code that query for the data and I do not wish to change each of them, I would like the definition to be system-wide.
Thanks for your help.
EDIT:
I wanted to add a clarification: When I wrote this, I was thinking of the direction of editing the mapping file. I thought that there might be a way to define the format there. That would mean changing in one place only, and not relying on any default format.
Thanks.
I think the use of a date formatter is always a good idea.
Date t_time = table1Entity.t_time;
String t_time_str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(t_time);
is possible, but less desired since I have a few places in the code that query for the data and I do not wish to change each of them, I would like the definition to be system-wide.
You have a timestamp in your database (non-varchar). You have a "timestamp" in your Java (non-String, probably a Date or Calendar). The difference is in the String/textual representation that the client is providing to you, be it psql, be it "toString()" method of your Java object. If you used a different database client, I bet the output would be a third variation :-)
My point is: you should not depend on the String representation of dates (or any other non-String object, for that matter). If any of your code depends on that, I'd say it's wrong. Period.
And if you need to touch more than one file to change how a date is represented as text for your end-user, then I'd say that you have an opportunity for change there: externalize the date format and free your code from "fixed" configuration.
In short: use splash's approach.
Hibernate doesn't have a datatype timestamp with time zone
, it has timestamp
and timezone
but that takes two fields, not just one field.
http://www.java2s.com/Code/Java/Hibernate/JavaTypeVSHibernateType.htm
精彩评论