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
Related
I tried to make a query withSpring data for updating an entry by id and I tried a lot options but still I can't get rid of this:
Named parameter not bound : table.eventDate
#Modifying
#Query(value = "update Table_name u set u.id = :table.id, u.event_date = :table.eventDate, u.client_id = :table.clientId, u.status = :table.status, u.status_date = :table.statusDate, u.creation_date = :table.creationDate, u.last_update_date = :table.lastUpdateDate where u.id = :table.id",
nativeQuery = true)
void updateEntity(#Param("table") Table table);
How should I write the query in order to get rid of this?
I tried a lot of posibilities online to write the query but nothing worked.
Correct native query statement:
#Modifying
#Query(value = "update Table_name u set u.id = :table.id, u.event_date = :table.event_date, u.client_id = :table.client_id, u.status = :table.status, u.status_date = :table.status_date, u.creation_date = :table.creation_date, u.last_update_date = :table.last_update_date where u.id = :table.id",
nativeQuery = true)
void updateEntity(#Param("table") Table table);
Since you're using a native query instead of a JPQL-Query, you have to write :table.event_date instead of :table.eventDate. Same counts for example :table.clientId, it has to be :table.client_id.
Hope it'll work!
Native Queries: Always snake_case instead of camelCase, unless your column names are in camelCase, but I doubt that. :)
I am a newbie to Spring and java, I have a scenario, where i like to query like below:
when i have a po.id value, i can search like this below:
form service :
prescriptionOrderRepository.searchPharmacyOrders(args);
I am writing my spring query like this:
#Query(value = "select po from PrescriptionOrder po WHERE po.pharmacyId = :pharmacyId "
+ "AND po.id = :idValue AND po.active = :active ORDER BY po.createdAt DESC")
Page<PrescriptionOrder> searchPharmacyOrders(#Param("pharmacyId") Long pharmacyId,
#Param("idValue") Long idValue, Pageable pageRequest, #Param("active") Boolean active);
Suppose if i have to requirement, po.id is an optional field means, how can write query for that.
I always expect the params, they're either null by default, or I get a value and it has to match. So for a parameter :idValue your query has
... AND (po.id = :idValue OR :idValue is null) ...
When e.g. you come from a Controller class, using GET variables, you can always use them as default null, or you're getting a value and it has to match.
In your example, that query in total...
WHERE (po.pharmacyId = :pharmacyId AND po.id = :idValue AND po.active = :active
Changes to:
WHERE ((po.pharmacyId = :pharmacyId OR :pharmacyId is null) AND (po.id = :idValue OR :idValue is null) AND (po.active = :active OR :active is null)
am trying to form a query based on parameters, if the parameters for WHERE clause is null or not. it seems to be a huge code if i do this on if and else. Is there any other smart way to this??
example :
String query = "SELECT CUSTOMER_NAME FROM CUSTOMER_TABLE WHERE ";
if(cust_id !=null && !(cust_id.trim().equalsIgnoreCase("")))
{
query = query + "cust_id='"+cust_id+"'";
}
else
{
}
checking all the columns like this, the code is looking like a mess, please let me know if there is an other way to do this
adding to the above question :
I also have the parameters for like operator
example
if(strCustName!=null)
{
String query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_NAME LIKE '"+strCustName+"';
}
You can use NamedParameterJDBCTemplate
And your query could be
... WHERE (cust_id=:custIdParam OR :custIdParam is null)
AND (another_column=:another_param OR :another_param is null)
UPDATE:
String sqlstr = "select * from the_table where lastname like :lastname or :lastname is null"
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(datasource);
Map namedParameters = new HashMap();
namedParameters.put("lastname", "%test%");
SqlRowSet result = jt.queryForRowSet( sqlstr ,namedParameters );
from the link
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).
I have the following criteria query:
String cat = "H";
Criteria criteria = currentSession().createCriteria(this.getPersistentClass()).
add(Restrictions.ne("category", cat)).
createAlias("employees", "emp").
createAlias("emp.company", "company");
Disjunction disjunction = Restrictions.disjunction();
for(Region r: regions){
disjunction.add(Restrictions.eq("company.region", r));
}
criteria.add(disjunction);
if(status != null) {
criteria.add(Restrictions.eq("status", status));
}
if (period != null) {
criteria.add(Restrictions.eq("period", period));
}
criteria.setProjection(Projections.groupProperty("id")) //this line was added to try to "fix" the error, but it still happened.
criteria.addOrder(Order.asc("id"));
I guess a query that explains my criteria query could be:
select n.* from NOMINATION n
join NOMINEE i on n.NOM_ID = i.NOM_ID
join EMPLOYEE e on e.EMP_ID = i.EMP_ID
join COMPANY c on c.COMPANY_CODE = e.COMPANY_CODE
where n.CATEGORY_CODE!='H' and (c.REGION_ID = ? or c.REGION_ID = ? or c.REGION_ID = ?) and n.STATUS_ID = ? and n.PERIOD_ID = ?
order by n.NOM_ID
What I am trying to do here, is pretty confusing but for the most part it works except when I add this specific line (though the query works fine):
criteria.addOrder(Order.asc("id"));
and then I get error:
java.sql.SQLException: Column "NOMINATION.NOM_ID" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
Which I suspect is something that has to do with SQL-SERVER. I am already grouping by id. So what am I doing wrong here, or should I just use HQL?
Your current query seems to be a simple Query which doesn't have any group function used or not a group by query. According to your current requirements you do not have to use this line.
criteria.setProjection(Projections.groupProperty("id")).addOrder(Order.asc("id"));
Or you have to modify your sql statements.