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
Related
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'}
I am trying to insert a record in a Oracle table using Java. The field in question is defined as a timestamp.
I am using a the following statement:
INSERT INTO MYTAB (UNIQUE_ID, CREATED_AT) VALUES ('137', ?)";
PreparedStatement updatePerf = connection.prepareStatement(updateString);
updatePerf.setTimestamp(1,getCurrentTimeStamp());
The getCurrentTimeStamp looks as follows:
private static java.sql.Timestamp getCurrentTimeStamp() {
long time = System.currentTimeMillis();
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
System.out.println("Time in milliseconds :" + timestamp);
return timestamp;
}
When the program runs, I still the correct timestamped printed with milliseconds:
Time in milliseconds :2014-05-13 15:40:03.076
However on the database, I only see
'137',2014-05-13 15:40:03
I want to retain the milliseconds desperately.
When you say "on the database, I only see", how are you getting the data out of Oracle? Have you proerly set NLS_TIMESTAMP?
Try setting:
NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH:MI:SS.FF'
in SQL*Plus, and then try the query, and see if you can see thw milliseconds component.
Alternately, you can format the timestamp column w/ a to_char() function:
select to_char(my_timestamp_col,'YYYY-MM-DD HH:MI:SS.FF') from my_table;
Note also, that if your column is timestamp with timezone, you'll need to set NLS_TIMETAMP_TZ_FORMAT instead.
table field status auto update when checking with system date and expirydate using query in mysql & java
In my table,
tbl-member:
id, name, expirydate,status are fields.
How to use this with TRIGGER
(expirydate,systemdate)
CREATE
TRIGGER autoupdation
trigger_time UPDATE
ON tbl-member FOR EACH ROW
trigger_body
how to create trigger_body for this function...
field expirydate check with system date and auto update the status field.
here is the code use function for check-updation
#Override
public List<Member> FindExpiredMembers() throws ParseException {
List<Member> memberlistforreturn=new ArrayList<>();
List<Member> memberlist=getAllMember();
java.util.Date utilDate=new java.util.Date();
java.sql.Date sqldate=new java.sql.Date(utilDate.getTime());
for(Member i : memberlist){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date exp_Date=sdf.parse(sqldate.toString());
java.util.Date renew_Date=sdf.parse(i.getRenewDate().toString());
if(renew_Date.compareTo(exp_Date)<0){
memberlistforreturn.add(i);
i.setStatus(true);
update(i);
}
}
System.out.println(memberlistforreturn.size());
System.out.println("working...!!!!!!");
return memberlistforreturn;
}
using this function the program run on slow
This should be part of your BEFORE UPDATE trigger.
for each row begin
if new.expirydate < curdate() then
set new.status = 1; -- still active
else set new.status = 0; -- expired
end if;
end;
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();
}
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();