Given that my native SQL query returns a single non-null result, can somebody help me evaluate using query.getSingleResult() vs using query.getResultList.get(0)
Just for example:
String queryStr = "Select count(id) FROM Job J where companyMaster = 3";
Query query = getEntityManager().createNativeQuery(queryStr);
return ((BigInteger) query.getResultList().get(0)).intValue();
produces the same result as:
String queryStr = "Select count(id) FROM Job Jo where companyMaster = 3";
Query query = getEntityManager().createNativeQuery(queryStr);
return ((BigInteger) query.getSingleResult()).intValue();
If you are using database method like getById then it is okay to use the getSingleResult method. In this case, you are sure that there is only one entity in the database matching that id.
But as you are performing a count, you should use the getSingleResult as it almost definitely will return you a result rather than using getResultList.get(0).
Related
String query = "SELECT distinct on (l->>'test_id') l->>'test_id' test_id,
l->>'result' result,l->>'indication' indication
FROM Ltable,
jsonb_array_elements(lines) with ordinality a(l) WHERE pat_id = ?
AND result_received <= ? AND (l->>'test_id' = ? OR l->>'test_id' = ? )
and archived = false ORDER BY l->>'test_id', result_received DESC LIMIT 2";
jdbcTemplate.query(query, rs -> {
while(rs.next()){
}
}val1, val2, val3, val4);
The above query when executed from pgAdmin returns some rows but when executed from a java app returns an empty resultSet, the line while(rs.next()) never gets entered.
I have logged the query parameters to make sure the correct data is being passed into the query.
Please help look at at and let me know if there's a mistake I'm making somewhere.
I am trying to get details of Properties details from database using JPQL, Hear I am writing where condition like (properties.IsDeleted <> 'Y' or properties.IsDeleted IS NULL)
but, in JPQL query it is not getting 'Y', but, it is was showing like '?' symbol. this is the problem I am getting. please help me from this issue.
the below code is showing query like:-
select properties0_.property_id as col_0_0_,
properties0_.property_type as col_1_0_, properties0_.property_name as
col_2_0_, properties0_.property_area as col_3_0_,
properties0_.property_city as col_4_0_, properties0_.no_of_rooms as
col_5_0_ from iot_property properties0_ where
(properties0_.is_deleted<>? or properties0_.is_deleted is null) and
properties0_.property_id=6
In the above query in bold mark shows properties0_.is_deleted<>? ,but what I want is properties0_.is_deleted<>Y
why that "Y" is not assigned to that query. that I am not understanding.
will you please help me to solve this issue.
Thanks
CriteriaBuilder deviceBuilder = propertySession.getCriteriaBuilder();
CriteriaQuery<Object[]> userCriteriaQuery = deviceBuilder.createQuery(Object[].class);
Root<Properties> propertyRoot = userCriteriaQuery.from(Properties.class);
Path<Object> pathPropertyId = propertyRoot.get("propertyId");
Path<Object> pathpropertyType = propertyRoot.get("propertyType");
Path<Object> pathpropertyName = propertyRoot.get("propertyName");
Path<Object> pathpropertyArea = propertyRoot.get("propertyArea");
Path<Object> pathpropertyCity = propertyRoot.get("propertyCity");
Path<Object> pathnumberOfRooms = propertyRoot.get("numberOfRooms");
userCriteriaQuery.multiselect(pathPropertyId, pathpropertyType, pathpropertyName, pathpropertyArea,
pathpropertyCity, pathnumberOfRooms);
Predicate userRestriction = deviceBuilder.or(deviceBuilder.notEqual(propertyRoot.get("isDelete"), "Y"),
deviceBuilder.isNull(propertyRoot.get("isDelete")));
Predicate userRestriction2 = deviceBuilder
.and(deviceBuilder.equal(propertyRoot.get("propertyId"), propertyId));
userCriteriaQuery.where(deviceBuilder.and(userRestriction, userRestriction2));
Query<Object[]> deviceQuery = propertySession.createQuery(userCriteriaQuery);
List<Object[]> resultList =deviceQuery.getResultList();
for(Object[] objects : resultList) {
Integer dbPropertyId = (Integer) objects[0];
String dbPropertyType = (String) objects[1];
String dbpropertyName = (String) objects[2];
String dbpropertyArea = (String) objects[3];
String dbpropertyCity = (String) objects[4];
Integer dbNoOfRooms = (Integer) objects[5];
System.out.println(dbPropertyId);
System.out.println(dbPropertyType);
System.out.println(dbpropertyName);
System.out.println(dbpropertyArea);
System.out.println(dbpropertyCity);
System.out.println(dbNoOfRooms);
}
There is no such thing as "the final JPQL that ultimately gets translated to the final SQL with inserted paramerters". How a JPA implementation generates the SQL is down to it, and parameters, in general, will never be substituted into any String. SQL has generated from expression trees etc, not a String. This is a criteria query so for parameters it will show "?" on the console.
If you want param values inserting in then do it yourself since it only makes sense to you
I have written codes to query result from database using GroovyRowResult:
query = "SELECT * FROM table.A"
println(Query.get(0).get('testid'))
the query result is
[num_slashes:exam, testid:64]
I have lines of code:
def countA = appitems.size()
println(countA)
I want to assert the CountA == SQL query result testid 64.
How do i extract the integer value 64 from the SQL query result?
GroovyRowResult use get(0) to get the first record then convert it to string as it is object.
To get the value at 'testid' use '.' after get(0)
def query = "SELECT * FROM table.A"
println(query.get(0).testid.toString())
def countitems = appitems.size()
println(countitems)
assert countitems == query.get(0).testid
I have the following DAO method:
public String getSomeTable(final String param1) {
String sqlString = "select * from table where name ilike ?";
Query query = this.getEntityManager().createNativeQuery(sqlString);
query.setParameter(1, "%param1%");
}
If param1 is null or empty then I want to select all entries from the table. What is the correct way to do this? I am currently using the following:
public String getSomeTable(final String param1) {
String sqlString = "select * from table where name = ?";
Query query = this.getEntityManager().createNativeQuery(sqlString);
if(param1 == null)
query.setParameter(1, "%%");
else
query.setParameter(1, "%param1%");
}
But this is not scalable. I have datatypes like integer, date, etc. I want to know if there is a way to skip checking for that parameter if it is null.
I was planning to use COALESCE(?, CASE WHEN ? = '' THEN '%%' ELSE '%?%') but I think ? can be used only once for a particular parameter. The next one > I write is linked to second param.
On SQL Server, I use something like this, perhaps you can translate it to postgres:
DECLARE #variable INT = NULL;
SELECT *
FROM sysobjects
WHERE
(1 = CASE WHEN #variable IS NULL THEN 1 ELSE 2 END)
OR
(id LIKE #variable);
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.