I am trying to just to have my query ordered by my time stamp column and I cant figure out what is going wrong?
String sql = super._jpaql + "where entity.unit.ua=:ua order by timestamp desc";
Query query = super._entityManager.createQuery(sql).setParameter("ua", ua);
List<UnitNotesEntity> list = (List<UnitNotesEntity>) query.getResultList();
It should be:
where entity.unit.ua=:ua order by entity.timestamp desc
Related
I have a Parameterized query that goes
String stmt = "SELECT * FROM bucket ... ORDER BY $sortCategory DESC";
Then I go:
ParameterizedQuery query = ParameterizedQuery.parameterized(stmt, JsonObject.create().put("sortCategory", "dateUploaded"));
It's not sorting properly. I even printed out query.statementParameters() and it's printing my parameters properly. It only worked when I did a hardcode ("ORDER BY dateUploaded DESC"). Not sure why this is the case.
Why isn't this working?
The problem happens because the query gets translated into something like this:
SELECT * FROM bucket ... ORDER BY 'date' DESC;
Which is probably not making reference to the date column but to the 'date' value.
You can try using an index representing the column position instead of specifying the column name.
String stmt = "SELECT date, column2, column3 FROM bucket ... ORDER BY $sortCategory DESC";
ParameterizedQuery query = ParameterizedQuery.parameterized(stmt, JsonObject.create().put("sortCategory", 1));
I'm triggering a query using HQL, normally it should return empty resultset as it doesn't have any records w.r.t it. But, it throws
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
My code is
String hql = "FROM com.pck.Person where userId = " + userId;
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<Dashboard> listUserDetails = query.list(); <-- Problem here.
I'm expecting list size is 0 because there are no records w.r.t userId passed.
What changes do I need to do?
Lets say the value of userId was "abc12"
Given your code, the value of the string called hql would become:
"FROM com.pck.Person where userId = abc12"
If you took the value of that string and tried to run it as a query on any database, most of them would fail to understand that abc12 is a string. Normally it would be interpreted as a variable.
As other users mentioned including the single quotes would produce the desired query, but the recommended way to assign parameter values is this:
String hql = "FROM com.pck.Person where userId = :id"
query.setParameter("id", userId);
Looks like you are missing single quotes around userid.
Try with "FROM com.pck.Person where userId = '" + userId + "'";
or
Use named parameters with query.setParameter("userid", userId);
Posting the full stacktrace would help if this doesn't solve.
I'm trying to write a hibernate query to search if table Room contains roomname which contains part of string.The string value is in a variable. I wrote a query to get exact room name from the table.
findRoom(String name) {
Query query = em.createQuery("SELECT a FROM Room a WHERE a.roomname=?1");
query.setParameter(1, name);
List rooms = query.getResultList();
return rooms;
}
In sql the query is something like this:
mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%"name"%' or '%"name"' or '"name"%'
");
I want to know the hql query for searching the table that matches my query. I can not use string directly, so the search query has to be veriable based and I need all three types in a query, if it's begin with name, or contains name or ends name.
I would do something like that:
findRoom(String name) {
Query query = em.createQuery("SELECT a FROM Room a"
+ "WHERE a.roomname LIKE CONCAT('%',?1,'%')");
query.setParameter(1, name);
List rooms = query.getResultList();
return rooms;
}
Use like instead of =:
Query query = em.createQuery("SELECT a FROM Room a WHERE a.roomname like ?1");
query.setParameter(1, "%"+name+"%");
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.
I want to retrieve data between two dates from MS Access using JDBC.
I have tried
String query= "SELECT lastlogin FROM loginHistory " +
"WHERE lastlogin BETWEEN #01/07/2013# AND #03/07/2013#"+
"ORDER BY lastLogin DESC";
I am not getting the desired results.
Whats the problem. please help me out !
Thank You.
got the solution by transforming the date format from 01/07/2013 to 2013/07/01
String query= "SELECT lastlogin FROM loginHistory " +
"WHERE lastlogin BETWEEN #2013/07/01# AND #2013/07/03#"+
"ORDER BY lastLogin DESC";
Thank You all for supporting me..
Query missed the " in the end and you added in the middle.
Try
String query= "SELECT lastlogin FROM loginHistory " +
"WHERE lastlogin BETWEEN #01/07/2013# AND #03/07/2013# "+
"ORDER BY lastLogin DESC";
Your SQL syntax is correct, but you have an extra quotation mark in the middle of your code, directly after the first date in the BETWEEN clause.
I am not getting the desired results.
I believe then your code compiles but you are not getting the resultset what you expect. Although your code posted over here misses a quotation mark. I believe that it is a typo , or else the code wouldn't have compiled itself.
Check if the date string in the query is in correct format . Execute the query as a PreparedStatement :
String query= "SELECT lastlogin FROM loginHistory " +
"WHERE lastlogin BETWEEN ? AND ?"+
"ORDER BY lastLogin DESC";
And set the date strings after formatting it properly using Date format. Also check what is the datatype for your column , is it VARCHAR/String or DATE etc. You can even use the format() in the sql query itself :
Select lastlogin From loginHistory where format(lastlogin,"dd/mm/yyyy")
BETWEEN format(#01/07/2013#,"dd/mm/yyyy") AND
format(#03/07/2013#,"dd/mm/yyyy") ORDER BY lastLogin DESC;