fetch records based on today's date - java

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();

Related

Insert jspinner time value to database

I have two jspinners. the one contains an HH:mm format and the other one is a simple number(int) spinner.
when SAVE button clicked I want to update a database table that contains the timeLimit (type time) and attempts (type int) columns. But I dont know how to save a jspinner value to a time type in my database.
String update = "Update qbank SET timeLimit = ? and attempts = ? where qbankID = ?";
preparedStatement = connection.prepareStatement(update);
preparedStatement.setTime(1, spinnerTime.getValue());
i tried the code above but the last part has an error saying spinnerTime.getValue is an object and setTime() requires a Time. How can I convert and object to time? or is there other way to insert a jspinner with time value to my database? any help would be appreciated!
It was just a simple overlooked problem. I just did this code.
Time time; int attempt;
time = (Time) spinnerTime.getValue();
attempt = Integer.parseInt(spinnerAttempt.getValue().toString());
String update = "Update qbank SET timeLimit = ? and attempts = ? where qbankID = ?";
preparedStatement = connection.prepareStatement(update);
preparedStatement.setTime(1, time);
preparedStatement.setInt(2, attempt);
preparedStatement.setInt(3, qbankID);
preparedStatement.executeUpdate();

Hibernate - compare DateTime field with Restrictions.like

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'}

Ebean query using setDistinct() does not work

I'm using an ebean query in the play! framework to find a list of records based on a distinct column. It seems like a pretty simple query but the problem is the ebean method setDistinct(true) isn't actually setting the query to distinct.
My query is:
List<Song> allSongs = Song.find.select("artistName").setDistinct(true).findList();
In my results I get duplicate artist names.
From what I've seen I believe this is the correct syntax but I could be wrong. I'd appreciate any help. Thank you.
I just faced the same issue out of the blue and can not figure it out. As hfs said its been fixed in a later version but if you are stuck for a while you can use
findSet()
So in your example use
List<Song> allSongs = Song.find.select("artistName").setDistinct(true).findSet();
According to issue #158: Add support for using setDistinct (by excluding id property from generated sql) on the Ebean bug tracker, the problem is that an ID column is added to the beginning of the select query implicitly. That makes the distinct keyword act on the ID column, which will always be distinct.
This is supposed to be fixed in Ebean 4.1.2.
As an alternative you can use a native SQL query (SqlQuery).
The mechanism is described here:
https://ebean-orm.github.io/apidocs/com/avaje/ebean/SqlQuery.html
This is from the documentation:
public interface SqlQuery
extends Serializable
Query object for performing native SQL queries that return SqlRow's.
Firstly note that you can use your own sql queries with entity beans by using the SqlSelect annotation. This should be your first approach when wanting to use your own SQL queries.
If ORM Mapping is too tight and constraining for your problem then SqlQuery could be a good approach.
The returned SqlRow objects are similar to a LinkedHashMap with some type conversion support added.
// its typically a good idea to use a named query
// and put the sql in the orm.xml instead of in your code
String sql = "select id, name from customer where name like :name and status_code = :status";
SqlQuery sqlQuery = Ebean.createSqlQuery(sql);
sqlQuery.setParameter("name", "Acme%");
sqlQuery.setParameter("status", "ACTIVE");
// execute the query returning a List of MapBean objects
List<SqlRow> list = sqlQuery.findList();
i have a solution for it:-
RawSql rawSql = RawSqlBuilder
.parse("SELECT distinct CASE WHEN PARENT_EQUIPMENT_NUMBER IS NULL THEN EQUIPMENT_NUMBER ELSE PARENT_EQUIPMENT_NUMBER END AS PARENT_EQUIPMENT_NUMBER " +
"FROM TOOLS_DETAILS").create();
Query<ToolsDetail> query = Ebean.find(ToolsDetail.class);
ExpressionList<ToolsDetail> expressionList = query.setRawSql(rawSql).where();//ToolsDetail.find.where();
if (StringUtils.isNotBlank(sortBy)) {
if (StringUtils.isNotBlank(sortMode) && sortMode.equals("descending")) {
expressionList.setOrderBy("LPAD("+sortBy+", 20) "+"desc");
//expressionList.orderBy().asc(sortBy);
}else if (StringUtils.isNotBlank(sortMode) && sortMode.equals("ascending")) {
expressionList.setOrderBy("LPAD("+sortBy+", 20) "+"asc");
// expressionList.orderBy().asc(sortBy);
} else {
expressionList.setOrderBy("LPAD("+sortBy+", 20) "+"desc");
}
}
if (StringUtils.isNotBlank(fullTextSearch)) {
fullTextSearch = fullTextSearch.replaceAll("\\*","%");
expressionList.disjunction()
.ilike("customerSerialNumber", fullTextSearch)
.ilike("organizationalReference", fullTextSearch)
.ilike("costCentre", fullTextSearch)
.ilike("inventoryKey", fullTextSearch)
.ilike("toolType", fullTextSearch);
}
//add filters for date range
String fromContractStartdate = Controller.request().getQueryString("fm_contract_start_date_from");
String toContractStartdate = Controller.request().getQueryString("fm_contract_start_date_to");
String fromContractEndtdate = Controller.request().getQueryString("fm_contract_end_date_from");
String toContractEnddate = Controller.request().getQueryString("fm_contract_end_date_to");
if(StringUtils.isNotBlank(fromContractStartdate) && StringUtils.isNotBlank(toContractStartdate))
{
Date fromSqlStartDate=new Date(AppUtils.convertStringToDate(fromContractStartdate).getTime());
Date toSqlStartDate=new Date(AppUtils.convertStringToDate(toContractStartdate).getTime());
expressionList.between("fmContractStartDate",fromSqlStartDate,toSqlStartDate);
}if(StringUtils.isNotBlank(fromContractEndtdate) && StringUtils.isNotBlank(toContractEnddate))
{
Date fromSqlEndDate=new Date(AppUtils.convertStringToDate(fromContractEndtdate).getTime());
Date toSqlEndDate=new Date(AppUtils.convertStringToDate(toContractEnddate).getTime());
expressionList.between("fmContractEndDate",fromSqlEndDate,toSqlEndDate);
}
PagedList pagedList = ToolsQueryFilter.getFilter().applyFilters(expressionList).findPagedList(pageNo-1, pageSize);
ToolsListCount toolsListCount = new ToolsListCount();
toolsListCount.setList(pagedList.getList());
toolsListCount.setCount(pagedList.getTotalRowCount());
return toolsListCount;

JPA query equivalent to mysql query

Below is mysql query which is working fine and giving me expected results on mysql console.
select * from omni_main as t where t.date_time BETWEEN STR_TO_DATE(CONCAT('2011', '08', '01'),'%Y%m%d') AND LAST_DAY(STR_TO_DATE(CONCAT('2012', '08','01'), '%Y%m%d')) group by year(date_time),month(date_time)
I need its JPA equivalent query. Below is what I am trying but its returning nothing.
String queryStr = "select * from OmniMainEntity o where o.dateTime BETWEEN STR_TO_DATE(CONCAT('"+fromYear+"', '"+fromMonth+"','01'), '%Y%m%d') AND "
+"LAST_DAY(STR_TO_DATE(CONCAT('"+toYear+"', '"+toMonth+"','01'), '%Y%m%d'))";
Query query = manager.createQuery(queryStr);
System.out.println("Result Size: "+query.getResultList().size());
Here fromYear, fromMonth, toYear, toMonth are method parameters using in creating queryStr.
Please suggest where I may wrong!
Any other way to achieve goal is also welcome!
As you are using JPA Query, it would be better to not use database-specified sql function, such as STR_TO_DATE.
You can have a try by this way.(A Hibernate way, JPA should be similiar):
First, you can parse a java.util.Date object from "fromYear" and "fromMonth" like below:
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date startDate = df.parse(fromYear + "" + fromMonth + "01");
Date endDate = df.parse(.....);
Then, set them into the JPA query.
String queryStr = "select * from OmniMainEntity o where o.dateTime BETWEEN :startDate AND :endDate)"; // The query now changed to database independent
Query query = manager.createQuery(queryStr);
query.setDate("startDate", startDate);
query.setDate("endDate", endDate);
At last, doing the search:
System.out.println("Result Size: "+query.getResultList().size());
Your query doesn't have a verb in it. You probably want SELECT in there:
SELECT o FROM OmniMainEntity o WHERE...
Also, you should be using parameterized and typed queries, and it's usual to use short names (o instead of omniMainEnt) to make your queries readable.

Older then query in java persistence

I need to do a query where i take things older then 5 days.(a custom date)
i have looked at HQL but since it is in persistence i dont have access to setTimestamp as per here
String hqlQuery;
Calendar minDate = Calendar.getInstance();
minDate.add(Calendar.DATE, -days);
hqlQuery = "select n from notifications where n.app_id=:app and ((n.sent_date<=:minDate) OR (n.sent_date is null)) and n.handled='N'";
is how i tried...
Any sweet helpers, thanks in advance :-)
Edit:
So i changed my method it now looks like this:
public static List<Notification> findOlderThen(EntityManager em, Long app, int days) {
String hqlQuery;
Calendar minDate = Calendar.getInstance();
minDate.add(Calendar.DATE, -days);
hqlQuery = "select n from notifications where n.app_id=:app and ((n.sent_date<=:minDate) OR (n.sent_date is null)) and n.handled='N'";
System.out.println(hqlQuery);
return em.createQuery(hqlQuery).setParameter("app", app).setParameter("minDate",minDate.getTime()).getResultList();
}
But it gives this error:
Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [select n from notifications where n.app_id=:app and ((n.sent_date<=:minDate) OR (n.sent_date is null)) and n.handled='N'], line 1, column 28: syntax error at [where].
Internal Exception: UnwantedTokenException(found=where, expected 80)
SessionFactory sf = // get your session factory
Query q = sf.getCurrentSession()
.createQuery(hqlQuery);
q.setParameter("minDate",minDate.getTime())
.setParameter("app", appId)
.list();
Would be how you set a date parameter, assuming type of sent_date is Date in Notifications model class. Also, on this part of your query select n from notifications, make sure notifications is the actual name of your class. Case matters! It should probably be select n from Notifications n.
Update:
You need to declare the alias for the class.
If I'm not mistaken, aren't you supposed to do something like this when you're adding dates in a query:
hqlQuery = "select n from notifications where n.app_id=:app and ((n.sent_date<=':minDate') OR (n.sent_date is null)) and n.handled='N'";
notice the ' around the minDate variable

Categories