Hibernate java Mysql date are not sync - java

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!.

Related

Comparing current date (Java) to a Timestamp in a DB (sql) using Hibernate

I am trying to check if an entry to the DB has occurred today. My Query works when I run it with MySqlWorkbench, but when I use hibernate the query does not seem to work correctly I am always returned true even though the DB does have dates today.
The query is:
#Query("SELECT CASE WHEN (count(ent) < 1) then true else false end
FROM Entity ent WHERE ent.createdAt >= (?1)")
boolean checkIfEnteredToday(Date date);
The date is from the java.sql.Date library.
I solved it by changing the DataType of The entity's datetype for 'created_at' to java.sql.Date, whereas previously it was java.sqlTimestamp.

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

Query using setDate does not find results - cannot see final-query with parameters

I have an SQL which looks into a dimension table (which stores every dates until year 2020) and then shall retrieve the todays row.
I watched into the table, todays date is in there.
The problem is, that SQL does not return any result.
I am thinking of a problem related to the use of java.sql.PreparedStatement.setDate method.
In past i think this was working fine, now I did some kine of regression test and it failed. The differences to the past are having Oracle 12 DB now instead of 11 in past and running it on CentOS 6.5 instead of AIX.
On search I found this topic here:
Using setDate in PreparedStatement
As far as I can see, I am doing as suggested.
Heres the java code and the query:
public static String SELECT_DATUM = "SELECT TIME_ID, DATE, DAY_NAME, WEEK_NAME, MONTH_NAME, YEAR_NAME, SORTING, RELATIONDATE, VALID_TO, VALID_FROM FROM DIM_TIME WHERE DATE = :date";
java.util.Calendar now = Calendar.getInstance();
now.clear(Calendar.HOUR);
now.clear(Calendar.MINUTE);
now.clear(Calendar.SECOND);
now.clear(Calendar.MILLISECOND);
Date tmpDate = now.getTime();
Date tmpDate2 = new Date(((java.util.Date)tmpDate ).getTime());
statement.setDate(1, tmpDate2 );
I notice that getTime() is called twice. But I dont think its that bad.
I also noticed some displaying formats:
in Database the date-colums shows me the date like this: '08.11.2015'
in java while debugging tmpDate2 shows me a date like this: '2015-11-08'
in java while debugging tmpDate shows me a date like this 'Sun Nov 08 12:00:00 CET 2015'
But again, these are just display formattings while it is a dateobject in background and a date-type in database. I would expect that je JDBC driver would map this itself without formattings, that why we are using setDate method and not setString.
What am I doing wrong? What could I do for further debugging to get it?
I would like see the resulting SQL query which is finally executed with the parameter.
I tried this sql on db isntance:
SELECT * FROM v$sql s WHERE s.sql_text LIKE '%select time%' ;
but only getting this then: "... where date = trunc(:1 )"
On this row at least I can see that it was using the right schema I expected it to use and where I checked whether todays date is available.
Edit:
something I found out:
I saw another code using the same function but giving an GregorianCalendar instead Calendar. When using
new GregorienCalandar();
instead of
Calendar.getInstance();
Theres no difference.
But when I assign a date and dont let the system take the current time, then it works:
Using
new GregorianCalendar(2015, Calendar.NOVEMBER, 8);
Would retrieve the row I want from SQL.
Zsigmond Lőrinczy posted this answer as comment:
Try this: SELECT TIME_ID, DATE, DAY_NAME, WEEK_NAME, MONTH_NAME,
YEAR_NAME, SORTING, RELATIONDATE, VALID_TO, VALID_FROM FROM DIM_TIME
WHERE DATE = TRUNC (:date) – 3 hours ago
This works for my problem.
I am writing this as reponse to check it later as answer on this question if hes not going to write his own response (to get the reputation-points).
But I am wondering how I could get the same by preparing on java.
The code uses the clear-methods, which where released into an own method named 'trunc'. I think the programmer intendet to do this instead of TRUNC in SQL. I am wondering if it werent possible to do so in java and if yes, how?
Edit:
And I am wondering why a TRUNC is needed at all. Because the column in Database is of type Date an not Timestampt. So wouldnt there be an automatically trunc? I would expect this. Why do I need a trunc on SQL?

Setting Date and Time into Oracle Date field using ebean

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.

Java play framework 2.0.4 ebean query

I am wondering how to query the database using the model in play 2.0 with a query like the one I listed below. I didn't see an option to pass in direct sql into the play framework 2.0.
I am trying to get a list of the expenses from a particular month.
SELECT * FROM Expensesdb.expense
WHERE month(expense.purchase_date) = 01
The option I see is to query for all the expenses and then parse each one for the month they are listed using the Date object.
I think there should be an efficient way, I can't seem to find a way to do this using ebean with Java play framework 2.0 to perform this query.
Update
Thanks Nico, I tried the exact code you have, with DateTime and I tried to use the code below, it doesn't return any Expenses. Am I doing something wrong?
Calendar calendar = Calendar.getInstance();
calendar.set(2012, 0, 01);
Date startDate = calendar.getTime();
calendar.set(2012, 0, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date endDate = calendar.getTime();
List<Expense> expenses = find.where().between("purchaseDate", startDate, endDate).findList();
return expenses;
I see two options:
1 - Using Ebean mapping
The idea is to search the expenses between the beginning and the end of the month, something like:
Datetime firstDayOfMonth= new Datetime().withDayOfMonth(1);
Datetime lastDayOfMonth = new Datetime().dayOfMonth().withMaximumValue();
return finder.where()
.between("purchaseDate", firstDayOfMonth, lastDayOfMonth).findList();
2 - Using RawSQL
For this, please take a look at the Ebean documentation.
The main drawback of raw sql is that this code will not be portable for different SQL servers (if you don't plan to use several db engine, it will not matter).
+1 for #nico_ekito
On the other hand, while you are suggesting getting all rows from DB and then parsing them in the loop, I'd rather suggest to parse them... while creating and store in format easier to search and index. Just create additional column(s) in your DB, and override save() and/or update(Object o) methods in your model, to make sure, that every change will set the field, ie use String purchasePeriod for storing string like 2012-11;
you can find then:
# in November of ANY year
SELECT * FROM table WHERE purchase_period LIKE '%-11';
# in whole 2012
SELECT * FROM table WHERE purchase_period LIKE '2012-%';
# in December 2012
SELECT * FROM table WHERE purchase_period LIKE '2012-12';
alternatively you can divide it into two Integer fields: purchaseYear, purchaseMonth.
For the first scenario the overriden save() method in the Expense model can look ie like this:
public void save() {
this.purchaseDate = new Date();
this.purchasePeriod = new SimpleDateFormat("yyyy-MM").format(this.purchaseDate);
super.save();
}

Categories