Hibernate - compare DateTime field with Restrictions.like - java

I have a createDateTime field with Date dataType in my entity class and hibernate generated a column with datetime type in the mysql table. Now, I need to compare createDateTime field with values without seconds. In fact, one user can enter for example 2015-01-01 12:10 in the search field and I want to show the record that has 2015-01-01 12:10:10 crateDateTime as a result. I know this is possible with flat query:
SELECT * FROM table_test WHERE crateDateTime LIKE "2015-01-01 12:10 %"
But I don't know how I can do this via hibernate.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
data = formatter.parse("2015-01-01 12:10");
//This returned null.
Criterion crtmp = Restrictions.like("createDateTime", data);
//This returned ClassCastException. Because second argument must have "Date" dataType not "String"
Criterion crtmp = Restrictions.like("createDateTime", data + "%");

You should create a Date variable e.g. createDateTimePlusOneMinute, than find a time range between your createDateTime and createDateTimePlusOneMinute, using the following restrictions
criteria.add(Restrictions.ge("createDateTime", createDateTime));
criteria.add(Restrictions.lt("createDateTime", createDateTimePlusOneMinute));

// datetime comparison
Select c from Customer c where c.date<{d '2000-01-01'}

Related

Fetching data from mysql database table based on condition of date

Can anyone suggest me the solution of fetching data on condition of current date which i am passing in dao layer method of type system current date.
for e.g I have to fetch data from table "X" which have a column "startdate" of Date type(Mysql) on the basis if that date is greater with the current date passed to the query in java.
I have tried with java.util.Date but not working and also my requirement is not to used database specific function like curr() or Now().
I found a relative post but none helped.Is there no alternative apart from using JodaTime.
Thanks.
In your Entity class mark 'startdate' field with
#Column(name = "startdate")
#Temporal(TemporalType.DATE)
private Date startdate;
And create query like this one:
#NamedQuery(name = "Entity.findAfterDate", query = "SELECT e FROM Entity e WHERE e.startdate >= :dateAfter")
In your EntityDAOImpl
public List<Entity> getEntitiesAfterDate(Date date) {
Query query = openSession().getNamedQuery("Entity.findAfterDate");
query.setParameter("dateAfter", date);
return query.list();
}

Sqlite group dates by day

I'm trying to retrieve a list of different days from table. They are stored in integer.
cal.getTime().getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
What I've written
select strftime('%d-%m-%Y'," + date_clmn + ") from "
+ TABLE_NAME +" group by strftime('%d-%m-%Y'," + date_clmn + ")"
Next, I convert these values toString.
What I get:
24-11--471
And after that when I try to make query with
strftime('%d-%m-%Y',date_clmn)=24-11--471
I get nothing.
What's wrong?
Will I run in trouble with timezone using this way?
If there are some other ways make it, I'll be glad to hear you.
Thanks in advance.
UPDATE
Tried "date(" + date_clmn+ ",'unixepoch')"
now retrieved value is "1970-01-01"
Since you are not storing a date in your table, you need to change your field. Try with this code:
"select strftime('%d-%m-%Y'," + date_clmn + "/1000,'unixepoch') from "
+ TABLE_NAME +" group by strftime('%d-%m-%Y'," + date_clmn + "/1000,'unixepoch')"
I'm adding this because I think it could be helpful to someone. As per documentation strftime() returns a string date in a given format. So in this clause:
strftime('%d-%m-%Y',date_clmn) = 24-11--471
^ ^
string this expression returns an integer
There's a type mismatch here that SQLite doesn't detect. Even query will run perfectly (I tested it and runs without errors), but of course it won't retrieve any row.
The right comparisson would be:
strftime('%d-%m-%Y',date_clmn) = '24-11--471'
Testing: Here's a little piece of code to test this behavior:
CREATE TABLE dateTest(myDate VARCHAR);
INSERT INTO dateTest(myDate) VALUES ('2013-08-29 18:57:00');
SELECT strftime('%Y-%m-%d',myDate) AS formatted, myDate FROM dateTest WHERE strftime('%Y-%m-%d') = 2013-08-29; /* this won't retrieve any row */
SELECT strftime('%Y-%m-%d',myDate) AS formatted, myDate FROM dateTest WHERE strftime('%Y-%m-%d') = '2013-08-29'; /* this will retrieve '2013-08-29 | '2013-08-29 18:57:00' */
And here's the output:

Unable to fetch result based on date range query

I want to fetch the record from HSQL database and query is as below:
ao.find(IssuesAD.class, Query.select().where("user=? AND (START_TIME = ? OR END_TIME = ? OR (convert(START_TIME,DATE) < convert(?,DATE) AND convert(END_TIME,DATE) > convert(?,DATE)) )",user,sqlDate,sqlDate))
// also tried by removing 'convert'
when i save or retrieve then i do convert java.util.date to java.sql.date format.
Above query works fine for retrieving the records match to exact date i.e. START_TIME=? or END_TIME=? but it does not work for date range (START_TIME < ? AND END_TIME > ?) even though records are existed.
In database records are existed as like - END DATE AS '2013-05-27 00:00:00.000000000', START DATE AS '2013-05-23 00:00:00.000000000'.
And parameter value is '2013-05-24' which between above record though unable to get retrieved in result.
Also, another records - END DATE AS '2013-05-30 00:00:00.000000000', START DATE AS '2013-05-23 00:00:00.000000000'.
And parameter value is '2013-05-28' and it should retrieve but did not..
Other stuff:
final java.sql.Date sqlDate = new java.sql.Date(startdatefield.getTime());
logger.info("final date sql date:" + sqlDate); //it prints as 2013-05-28
for (IssuesAD pi : ao.find(IssuesAD.class, Query.select().where("user=? AND (START_TIME = ? OR END_TIME = ? OR (convert(START_TIME,DATE) < convert(?,DATE) AND convert(END_TIME,DATE) > convert(?,DATE)) OR (convert(START_TIME,DATE) > convert(?,DATE) AND convert(END_TIME,DATE) < convert(?,DATE)))",user,sqlDate,sqlDate)))
{
....
}
In database - START_DATE and END_DATE both fields are type of "DATETIME".
Any idea what is wrong here...
Thanks

Cant insert an empty date value into mysql

String datum = datumInvoer.getText();
**String bdate = bdatumInvoer.getText();**
String[] speler = spelers.getSelectedItem().toString().split(" ");
String[] toernooi = toernooien.getSelectedItem().toString().split(" ");
try {
PreparedStatement query = con.prepareStatement("INSERT INTO `fullhouse`.`inschrijving_toernooi` ( `IT_datum`, `IT_betaaldatum`, `speler`, `toernooi`) VALUES (?, ?, ? ,?)");
query.setString(1, datum);
query.setString(2, bdatum);
query.setString(3, speler[0]);
query.setString(4, toernooi[0]);
query.execute();
i have set the default to NULL , but it still wont insert it i am close to changing the datatype to varchar.
ERROR: incorrect date value
delimiter $$
CREATE TABLE `inschrijving_toernooi` (
`IT_code` int(11) NOT NULL AUTO_INCREMENT,
`IT_datum` date DEFAULT NULL,
`IT_betaaldatum` date DEFAULT NULL,
`speler` int(11) NOT NULL,
`toernooi` int(11) NOT NULL,
PRIMARY KEY (`IT_code`),
UNIQUE KEY `aaa` (`speler`,`toernooi`),
KEY `FS_code_idx` (`speler`),
KEY `FT_code_idx` (`toernooi`),
First Convert your date parameter from string to date. For that follow code below.
String bdate = bdatumInvoer.getText();
// get the correct date Format
// follow the link to get correct date format
// throws ParseException
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(bdate);
Class SimpleDateFormat API
Now in prepared statement set them as date like shown below. As your table structure allows date in table.
query.setDate(2, date);
Now you still want to set null to that column then you can use and tell your query to set null by using following format in prepared statement.
query.setNull(2, java.sql.Types.DATE);
OR
query.setDate(2, null);
setNull API
Mapping of java.sql.Types to SQL types
I think this will solve your issue.
You need to change how you are passing parameters to you prepared statement
It should be something like below. And datum and bdatum should be of type Date. If you do not use what types are defined in your db you could put pass invalid data to your sql which would cause exceptions.
query.setDate(1, datum);
query.setDate(2, bdatum);
query.setInt(3, speler[0]);
query.setInt(4, toernooi[0]);
I suspect your bdatum variable contains an empty string. If you want to insert a SQL null, you need to pass in null, not empty string. (When I tried this on my machine with a similar insert, I got an "Incorrect date value" when trying to insert an empty string, but not with a null.)
if ("".equals(bdatum))
bdatum = null;
ps.setString(2, bdatum);
When you pass in a string in JDBC for a date value, MySQL will try to parse it, but empty string ("") is not a valid value. This works similarly to if you tried to do an insert with a date literal:
INSERT INTO `some_table` (`some_nullable_date_column`) VALUES ('2000-01-01') -- this works
INSERT INTO `some_table` (`some_nullable_date_column`) VALUES (NULL) -- this works
INSERT INTO `some_table` (`some_nullable_date_column`) VALUES ('') -- this fails
As an aside, passing in a string for a date value is semantically wrong and possibly less robust than parsing the string to a Date object before passing it to the PreparedStatement.

fetch records based on today's date

I wish to generate reports for my application, one such report requires to display list of orders given today. For that I have the following method in my ejb which returns nothing (debugged and found so):
public Collection<OrderStock> getOrderReport(String userName) {
String strQuery = null;
strQuery = "Select o from OrderStock o where o.userName.userName = :userName and o.orderDateTime = :orderDateTime";
Collection<OrderStock> c = em.createQuery(strQuery).setParameter("userName",userName).setParameter("orderDateTime", new Date(),TemporalType.DATE).getResultList();
return c;
}
How do i solve it? Why does it return nothing?
edited:
I am using mysql as backend
datatype of orderDateTime is DateTime
eg os data in orderDateTime : 2012-06-05 00:12:32
2012-06-05 11:34:42
2012-04-05 12:32:45
You have a DateTime column, and are looking for posts on a single date. I suspect this datetime column contains seconds or miliseconds since the Epoch. You can't compare times to dates, so you will have to convert the day to a time. Actually two times that describe the day.
SELECT o
FROM OrderStock o
WHERE
o.userName.userName = :userName
AND (
o.orderDateTime >= FirstSecondOfTheDay
OR o.orderDateTime <= LastSecondOfTheDay
)
Depending on your database system you can calculate these seconds (or milliseconds, i don't know your table) using the database or rather do it in java
You can not use Date() as simple as that. The date persisted in the DB will definitely have different format. So the best thing to do is to look into the method used to persist the data in the first place and use the same method to fetch back the data.
The method might by Oracle function, java method. You need to investigate further into this.
Try this for MySQL:
strQuery = "Select o from OrderStock o where o.user.userName = :userName and date(o.orderDateTime) = :orderDateTime";
Date today = DateUtils.truncate(new Date(), Calendar.DATE);
Collection<OrderStock> c = em.createQuery(strQuery).setParameter("userName",userName).setParameter("orderDateTime", today ,TemporalType.DATE).getResultList();

Categories