Setting Date and Time into Oracle Date field using ebean - java

Good old date/time problem which I can't to solve with good style...
DB: Oracle 11g
Table contains field: upd_date with Oracle type DATE - I can't change it to TIMESTAMP
My Ebean model:
#Column(name="UPD_DT")
public Timestamp uploadedAt;
I'm trying to save model with current timestamp and then check which value has been saved:
model.uploadedAt = new Timestamp(System.currentTimeMillis());
model.save();
System.out.println("Time before save:" + model.uploadedAt);
System.out.println("Time after save:" + Models.byId(model.id).uploadedAt;
And getting following results:
Time before save:1391633542210
Time after save:1391633542000
I'm know that the difference in these fields because of Oracle DATE doesn't have milliseconds part, but if I will try to update this model object without changing uploadedAt field - I will get: javax.persistence.OptimisticLockException: Data has changed.
Is there any correct way to declare fields in JPA models for Oracle Date field with date and time included, when I don't need to change TimeSpamp every time when I want to update object?
P.S. : Creation like new Timestamp((System.currentTimeMillis()/1000)*1000); looks ugly and all others solution with cutting milliseconds in TimeStamp are very heavy.
I'm trying to find short and clear solution when I don't need to think about superfluous milliseconds.

Related

Could not save date field as ISO date in mongo db via Camel (Caused by: java.lang.IllegalArgumentException: Invalid BSON field name $date) [duplicate]

We are trying to insert a document with the current date as it's field. We are writing in java using eclipse plugin for mongodb. We want to execute the Date() command of mongo to get the date from mongo and not from java.
How can I execute this mongo query?
db.example.insert({"date":new Date()})
I found this question in a previews question but the answer was not helpful
Link
The standard driver takes java.util.date types and serializes as BSON dates. So with a collection object to "example"
Date now = new Date();
BasicDBObject timeNow = new BasicDBObject("date", now);
example.insert(timeNow);
If you are looking for a way to use the "server" time in operations, there is the $currentDate operator, but this works with "updates", so you would want an "upsert" operation:
BasicDBObject query = new BasicDBObect();
BasicDBObject update = new BasicDBObject("$currentDate",
new BasicDBObject("date", true)
);
example.update(query,update,true,false);
Since that actually is an update statement, you need to be careful that you are not actually matching any documents if you intend this to be an insert only. So it would be best to make sure your "query" contains unique information, such as a newly generated _id or something equally unique.
You can do it trying something like this:
db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});
Use this:
db.example.insert({"date":new Date(Date.now())});
There is a key difference I noted when using Date() as follows.
{ dateWhenCreated : Date() }
vs
{ dateWhenCreated : new Date() }
Notice the "new" keyword in the second usage. Whereas the first usage loads the data "as a string", the second one loads date as a field with date data type.
This might impact your sorting capability - dates stored as strings don't get sorted the same way as dates stored as dates.
Per the mongodb documentation here

JPA + PostgreSQL: Only time being persisted

I have a PostgreSQL table containing a timestamp without time zone field. This is configured in my Java code as follows:
#Column(name = "timestamp")
#Temporal(TemporalType.TIMESTAMP)
private java.util.Date timestamp;
The timestamp property is being set to new Date() i.e. containing both the date and the time. However in the database the date part is not being persisted e.g. "14:40:28.889"; therefore when it is retrieved from the database the date is not loaded and set to default i.e. 01/01/1970. Any ideas where the date part of the timestamp is running off to?
UPDATE:
I increased the logging level for hibernate so I can see what is being persisted by adding the following in the application.properties file:
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
The log output was as follows:
binding parameter [6] as [TIMESTAMP] - [Wed Sep 16 08:57:03 CEST 2015]
UPDATE 2:
I stepped through the code and found the insert sql with the date formatted as 2015-09-16 11:16:09.416000 +02:00:00. I insert the string automatically in PGAdmin and it insert with no error. After save a clicked the little refresh button and the date part disappeared! So the data is being persisted correctly but somehow postgre is doing something weird afterwards.
This was one of the silliest mistakes ever, I had a script that creates the tables and it was marked as "time without timezone" i.e. not timestamp so PostgreSQL was obviously removing the date. I will leave this question as it might help someone debug similar issues.

Getting unexpected time with AM instead PM and viceversa after getting Timestamp column from MySQL database

I have a column in my table with timestamp datatype and the value for instance look like '2014-08-30 00:00:50'. From database point of view I know it's showing the time of 12:00:50 AM for '00:00:50' and 12:00:50 PM if the value is 2014-03-30 12:00:50. But When I process the data in my application by fetching the table values, I'm getting AM for the time which has to be PM. I want to know how could I achieve this? I also want to know that the problem weather it is from my application side ? or database side? Could I achieve this If I get time from database as unixtimestamp format?
I've seen several questions related to this but I found none of them led me to solve this issue. Please help
If you are getting the date as a string you can do the following to convert it to AM/PM.
String s = "2014-08-30 00:00:50";
SimpleDateFormat d = new SimpleDateFormat("y-MM-dd H:mm:s");
Date in24HrFormat = d.parse(s);
String in12HrFormat = new SimpleDateFormat("y-MM-dd h:mm:sa").format(in24HrFormat);
System.out.println(in12HrFormat);

Hibernate java Mysql date are not sync

I have a java code using Hibernate and Mysql.
I cant understand what happens to Dates between Mysql and Java? for example can any body explain why is the output of this code is true????
Date d = something!
Query q= HSF.get().getCurrentSession().createQuery("from BaseNotification where creationDate <= :maxd and creationDate >= :mind order by creationDate");
q.setDate("maxd",new Date(d.getTime()+23*3600*1000+1155*1000));
q.setDate("mind",new Date(d.getTime()+23*3600*1000+1154*1000+999));
((BaseNotification)q.list().get(0)).getCreationDate().equals(d); // why its true!!!!!!!
believe me I'm not kidding!!!!
also if i get an object from hibernate with some date property and then want to get all objects with that date it doesn't even return the object itself!
my timezone is +3:30 is there any thing related to it?
but DB and Java code are in the same machine!.

hibernate criteria for a time range search on a Date field

Im using Oracle 10g,Hibernate 3,springMVC, jqgrid. I have some Date fields in ORACLE which are mapped as follows
#Temporal(TemporalType.DATE)
#Column(name = "DOC_CREATION_DATE", length = 7,insertable=true,updatable=false)
public Date getDocCreationDate() {
return this.docCreationDate;
}
In my grid I filter date using jqueryCalendar and everything is fine. now I have a new request from the client which is to show the time of documentCreation and they also want to be able to filter by a time range. for example:
find all records created between 6:am and 7:pm, find all records created at 6:am.
I have tried already formatting the date field with
#Temporal(TemporalType.TIMESTAMP)
and that's not what they want
Is there any other approach to this problem, any good ideas how to implement this are very welcome.
the thing is I need to use the same mapped field to query in one column of the Jqgrid for the regular date(12/01/2012 using jqueryCalendar)and add another column for the time part of that same mapped field once that is done I need to query (hibernate criteria) the time column for a range of time
something like this mock:
...
criteria.add(Restrictions.ge("docCreationDate.mappedFieldTimePart",6AM ));
thank you for all the help
The column is of type mapped to a Time, and thus you must compare its value with a Time:
Time sixAM = Time.valueOf("06:00:00");
criteria.add(Restrictions.ge("docCreationDate.mappedFieldTimePart", sixAM));
You can also use a regular date:
Date sixAM = new SimpleDateFormat("HH:mm").parse("06:00");
criteria.add(Restrictions.ge("docCreationDate.mappedFieldTimePart", sixAM));
You must change the #Temporal annotation to use either TemporalType.TIMESTAMP or add another field and annotate it with TemporalType.TIME. Hibernate uses the #Temporal annotation to determine if the field is to be treated like a java.sql.Timestamp or a java.util.Date with the time lopped-off (set to midnight, or 00h 00m 00.0s). This allows developers to use java.util.Date everywhere in their application and never have to worry about the Timestamp class (it's banished from most of our codebase).

Categories