I am facing some issue with the following query.
for (String string : projects) {
String sql = "SELECT eff.id,eff.taskNo,eff.projectId,sum(eff.hours),eff.employeeId FROM EffortCalculator eff where eff.projectId='"
+ string + "' and eff.dayDate >= '2014-12-15' and eff.dayDate <= '2014-12-16' GROUP BY eff.projectId";
System.out.println("sql" + sql);
SQLQuery query = session.createSQLQuery(sql);
System.out.println(query.list());
// query.addEntity(EffortCalculator.class);
list.addAll(query.list());
}
When I execute this query in MySQL DB it works fine. It actually contains two rows. But when I use this query in hibernate it gives empty list.
Related
Use jpa nativequery multiple columns in object list array
List<Object []> queryList = new ArrayList<>();
String[] arr = {"val1", "val2"};
queryList.add(arr);
String sql = SELECT * FROM TABLE A WHERE (A.COL1, A.COL2) IN (:queryList)
Query query = entityManager.createNativeQuery(sql);
query.setParameter("queryList", queryList);
In postgresql like this
SELECT * FROM TABLE A WHERE (A.COL1, A.COL2) IN (('val1', 'val2'), ('val3', 'val4'));
Here is the Exception
Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: record = bytea
建議:No operator matches the given name and argument types. You might need to add explicit type
Is this possible?
I would try to restructure the query as follows:
SELECT * FROM TABLE A
WHERE (A.COL1 = 'val1' and A.COL2 = 'val2')
OR (A.COL1 = 'val3' and A.COL2 = 'val4')
This would allow the query to be constructed as follows:
List<String[]> queryList = new ArrayList<>();
String[] arr = {"val1", "val2"};
String[] arr = {"val3", "val4"};
queryList.add(arr);
String sql = "SELECT * FROM TABLE A "; //dont forget space at end
if (!queryList.isEmpty()){
sql = sql + "WHERE "; //dont forget space at end
for (String[] queryParam : queryList ){
sql = sql + " (A.COL1 = '"+ queryParam[0] + "' and A.COL2 = '" + queryParam[1] + "') OR "; //dont forget space at end and simple colons for param
}
//finally remove the last OR.
Integer indexLastOR = sql.lastIndexOf("OR");
sql = sql.substring(0, indexLastOR);
}
Query query = entityManager.createNativeQuery(sql);
This will also allow the query to be implemented without being native, which is advisable to maintain the JPA philosophy.
I am using Realm (version 0.87). I want to convert the sql query
Select * from Users where 'firstname' + " "+ 'lastname' like "Ranjana Dangol".
I tried it as
RealmQuery<UserEntityData> query = realm.where(UserEntityData.class).beginGroup();
String searchQuery = "Ranjana Dangol"
String[] queries = searchQuery.split("\\s+");
for(String username : queries){
query.equalTo(UserEntityData.FIRST_NAME, username, Case.INSENSITIVE)
.equalTo(UserEntityData.LAST_NAME, username, Case.INSENSITIVE);
}
I'm using hibernate in my project and I'm trying to convert an existing sql query from DaoImplementation class to hql,
The sql query I have is
JdbcTemplate select = new JdbcTemplate(dataSource);
String sql = "SELECT * FROM (SELECT site_id,rtc,sigplan,cycle_time,health,phase_no,phase_time,active_groups,groupscolour,ip "+
"FROM status_data where rtc>='" + fromDate + "' and rtc<'" + toDate + "' and "+
"site_id=" + SiteId + " order by rtc desc limit "+recordLimit+" )as temp ORDER BY RTC ASC";
I wrote the hql version to get data from HealthLog table as
String hql = " select f from (select h from HealthLog h where rtc>='"+fromDate+"' and rtc <'"+toDate+"' "
+ "and siteId = "+siteId+" order by rtc desc limit "+limit+" ) as f order by rtc asc ";
return super.readListByHql(hql);
But the above hql throws the following exception
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 16 [ select f from (select h from com.traff.hibernate.model.HealthLog as h where rtc>='1974-08-01 14:10:00.0' and rtc <'1974-09-01 23:46:20.6' and siteId = 20 order by rtc desc limit 50000 ) as f order by rtc asc ]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:79)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:276)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
at org.hibernate.hql.intern
I also tried the below code snippet but that giving me wrong results
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.ge("rtc", fromDate));
criteria.add(Restrictions.lt("rtc", toDate));
criteria.add(Restrictions.eq("siteId", siteId));
criteria.setMaxResults(limit);
criteria.addOrder(Order.asc("rtc"));
criteria2 = criteria;
criteria2.addOrder(Order.desc("rtc"));
return criteria2.list();
Which is the correct way to achieve the result?
First of all, as already mentioned in the comments, you cannot do a subquery within the FROM clause in HQL.
See: Hibernate Documentation
Secondly, the limit keyword is not supported by HQL.
Usually you would use query.setFirstResult(0) and query.setMaxResults(recordLimit) methods where query has the type of the Query Interface. But since you are using the limit in a subquery, there is no way.
See: How to set a limit to inner query in Hibernate?
Some options:
Use a native SQLQuery
Since you are only sorting in the outer Query. You could only execute the inner query and sort in Java.
Example for Option 2:
Session session = factory.openSession();
Query query = session
.createQuery("FROM HealthLog "
+ "WHERE rtc >= :rtcL and rtc < :rtcG and siteId = :siteId "
+ "ORDER BY rtc DESC");
query.setParameter("rtcL", fromDate);
query.setParameter("rtcG", toDate);
query.setParameter("siteId", siteId);
query.setFirstResult(0);
query.setMaxResults(recordLimit);
List<HealthLog> res = query.list();
session.close();
Collections.sort(res, new Comparator<HealthLog>() {
public int compare(HealthLog o1, HealthLog o2) {
return o1.getRtc().compareTo(o2.getRtc());
}
});
The query above returns HealthLogs with all attributes. If you want to only retrieve specific attributes, you can add a SELECT new HealthLog(siteId,rtc,sigplan,cycle_time,...) to your Query with a fitting constructor in HealthLog.
Please note that the code snippet might not be ready to use, since i do not know your model and attribute names.
Using com.couchbase.client, java-client version 2.2.7 I have been unable to get a n1ql query working that uses an IN statement with multiple items see my example query and java code below
public int getCountForDuration(Long startTime, Long endTime, String ids){
JsonObject placeHolders = JsonObject.create().put("ids", ids).put("startTime", startTime).put("endTime", endTime);
N1qlQuery query = N1qlQuery.parameterized(COUNT_STATEMENT, placeHolders)
N1qlQueryResult result = bucket.query(query);
...
}
public static final String COUNT_STATEMENT = "select count(*) as count " +
"from bucketName " +
"where docType = 'docId' " +
"and (id IN [$ids]) " + <----- OFFENDING LINE
"and publishTimestamp between $startTime and $endTime";
I've tried setting ids using ('), ("), and (`) such as:
ids = "'123', '456'";
ids = "\"123\" , \"456\";
ids = "`123`,`456`";
None of these are working when there are multiple ids however if there is only one such as ids = "'123'" it works fine. Also my query works if I use it using CBQ on the terminal.
My question is this how do I crate a parameterized N1QL query which
can take multiple items in an IN statement?
Removing the brackets around the $ids in the statement and putting the actual ids into placeholders as a JsonArray object should work:
JsonObject placeHolders = JsonObject.create()
.put("ids", JsonArray.from("id1", "id2", "id3"))
.put("startTime", startTime)
.put("endTime", endTime);
I'm able to set variable values for "where" restrictives:
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where test.col = :variableValue ");
criteria.setInteger("variableValue", 10);
But is it possible to set variable column like this?
String variableColumn = "test.col1";
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where :variableColumn = :variableValue ");
criteria.setInteger("variableValue", 10);
criteria.setString("variableColumn", variableColumn);
This is the result:
Exception in thread "main" Hibernate: select .... where ?=? ...
org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
...
at _test.TestCriteria.main(TestCriteria.java:44)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value 'test.col1' to data type int.
...
UPDATE (working solution):
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where (:value1 is null OR test.col1 = :value1) AND
(:value2 is null OR test.col2 = :value2) "
Does this make sense in your application:
String query = "select test.col1, test.col2, test.col3" +
"from Test test " +
"where {columnName} = :variableValue ";
Object variableValue = // retrieve from somewhere
String columnName = // another retrieve from somewhere
query = query.replace("{columnName}", columName);
// Now continue as always
This is generally a naive query constructor. You may need to refactor this idea to a separate utility/entity-based class to refine (e.g. SQL injection) the queries before execution.
You can set the column name as part of the string. For security you may do the SQL escaping manually, but at the end you can achieve this.
To avoid SQL injection you can use commons class:
String escapedVariableColumn = org.apache.commons.lang.StringEscapeUtils.escapeSql(variableColumn);
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where " + escapedVariableColumn + " = :variableValue ");
criteria.setInteger("variableValue", 10);