I was originally doing a single variable query and I had to add in another variable to my statement and can't seem to get it to work correctly or find a straight answer on the expected syntax. I've already checked everything is mapped correctly and nothing null is going into the query.
Here's what I'm attempting to do which isn't working correctly
return getHibernateTemplate().find("from Pricing_Data where rate_class=?", rate_class + "where utility=?", utility);
Orginally I had it as this and that was working as expected
return getHibernateTemplate().find("from Pricing_Data where rate_class=?", rate_class);
Try this:
return getHibernateTemplate().find("from Pricing_Data where rate_class=? AND utility=?", new Object[]{rate_class, utility});
Hibernate Find method
Try to use query
from Pricing_Data where rate_class = ? and utility = ?
Then setParameter for rate_class and utility.
SQL/HQL queries can have second (third, etc) where clause only in subqueries.
Related
I'm currently having a little issue with JPA 2 and Typed Query.
I'm creating a search feature in my project using LIKE clause, however when I try to search for a string like "marina" it no works, it works only when I type "marin", even when exists in the database the name marina.
This is my code:
StringBuilder builder = new StringBuilder("select u from User u"
+ " where (u.login LIKE :regex OR u.fullname LIKE :regex)"
+ " AND (u.status <> :status)"
+ " order by u.fullname");
TypedQuery<User> query = jpaAPI.em().createQuery(builder.toString(),User.class);
query.setParameter("status", statusTypeDeleted());
query.setParameter("regex", "%"+regex+"%");
query.setFirstResult(init);
query.setMaxResults(end);
So, does anyone know where is the problem?
Ok. I solved this problem right now.
The problem is on this line:
query.setFirstResult(init);
The value I was passing to this method was 1 instead 0. How just exist only one entity with name "marina", the query result nothing, since the first result should be 0.
Am running a query from JAVA , the query contains DATEDIFF function in which the parameter is a keyword,we can give yy,mm,day,etc.. so am getting these keyword from user as parameter and setting it in query, but the issue is it wont execute, it gives an exception as Invalid parameter for argument 1. If i run the same query in CLIENT it gives result, but if i give quotes to keyword like 'day' it gives the same error in CLIENT also. So my question how will I set it in the query from JAVA. Currently am doing like
for (String param : params) {
try {
namedParameterStatement.setObject(param,requiredFilterValues.get(param));
} catch (RuntimeException e) {
}
}
This is the query am using
SELECT CUST_KEY,Eff_Date_From,Eff_Date_To, DATEDIFF(:intervals,Eff_Date_From,Eff_Date_To) as datediffs,Active FROM CUSTOMER_DIM WHERE Active = :active
Am passing values for params intervalsand active, The issue is with :intervals as it takes keywords.
I think the java program setting the parameter as string that is why its generating error.. How can i implement this?
The problem is that you can only pass values using parametrized queries. You can't pass keywords (nor object names). In the case of your query. they would be passed as the equivalent of DATEDIFF('<your-keyword>', .., which wouldn't work either.
There is no solution except manually concatenating the required keyword into the query, or creating a convoluted query using a CASE-construct to get the right value depending on the value passed:
case ? when 'MONTH' then datediffer(MONTH, ..) when .. end
You may need to explicitly cast the parameter to a VARCHAR to get it to work.
In my Case after getting a certain list I need to to iterate that list to set some other fields of the POJO class.
if (transportHeaderList.get(i) instanceof TransportHeaderIiss){
transHeadIiss=(TransportHeaderIiss)transportHeaderList.get(i);
customerVendor= tOManagementDAO.getVendorCode(transHeadIiss.getCustVendUid());
}
if(customerVendor!=null){
transHeadIiss.setVendorCode(customerVendor.getCustVendCode());
}
The Above code calls getVendorCode method to get custVendorCode value from the database. The code for getVendorCode is as follows
public CustomerVendorIiss getVendorCode(Long custVendUid) {
List list=new ArrayList();
/* Criteria criteria = sessionFactory.getCurrentSession().createCriteria(CustomerVendorIiss.class);
criteria.add(Restrictions.eq("companyCode",user.getDefaultCompany().getCompanyCode()));
if(custVendUid!=null && custVendUid.intValue()>0)
{
criteria.add(Restrictions.eq("custVendUid",custVendUid));
}
list=criteria.list();*/
UsersIiss user= ApplicationContextProvider.getLoggedInUser();
String sqlQuery="select custVendCode as custVendCode from CustomerVendorIiss where companyCode ='"+ user.getDefaultCompany().getCompanyCode() +"' and custVendUid= "+custVendUid;
Query query = sessionFactory.getCurrentSession().createQuery(sqlQuery);
query.setResultTransformer(Transformers.aliasToBean(CustomerVendorIiss.class));
list=query.list();
if(list.size()>0){
return (CustomerVendorIiss)list.get(0);
}else{
return null;
}
}
When I executed above code with criteria, it took a lot time to get the values from table and set it to POJO class and sometimes I would get java.lang.OutOfMemoryError: Java heap space error . I guess that's because I am not de-allocating the criteria object.
when I executed the above code using createQuery() method I did not run into that issue and all that process of getting and setting was faster.
I want to understand what is that I am doing wrong here?
it would be great to know how and when criteria is better or HQL is better ?
Thank you !!
Actually these queries are different. The second one has an additional restriction
companyCode ='"+ user.getDefaultCompany().getCompanyCode() +"'
So try to add the same to the criteria
criteria.add(Restrictions.eq("companyCode",user.getDefaultCompany().getCompanyCode()));
Also it's not god to concate strings this way to get the query. SQL injection is possible. Use parameters instead.
Criteria and HQL is better than SQL in one case - you need DB independent logic to swap DB when necessary without rewriting code.
I use MySQL 5.5 with Hibernate 3.6 and JPA 2.0. I have a User table with a firstName which could also be null or an empty string. I want to have those empty firstName results last in my search results. For that I wrote the following SQL query which works just fine:
SELECT * FROM User ORDER BY ISNULL(firstName), firstName = "", firstName ASC LIMIT 100
Now want to translate this to JPA using the criteria API and I am not quite so sure about the order by. Here is what I have:
criteriaQuery = criteriaQuery.orderBy(cb.asc(cb.isNull(users.get(User_.firstName))), cb.asc(cb.equal(users.get(User_.firstName), "")), cb.asc(users.get(User_.firstName)));
However, the code snippet above does not work, because the CriteriaBuilder.isNull() method is traslated to IS NULL and not to the ISNULL() function of MySQL. I get the following exception:
org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: is null
Any ideas on how to check for null in the Order by statement with JPA 2.0
That is not possible. In JPA you can ORDER BY fields only that you select (that are in the SELECT part of your query). The problem is that there is no IS_NULL function, that can be used in the SELECT part.
I got the exact same problem as you do, finally I solve it using this way, maybe you can try:
CriteriaQuery<> query;
query.orderBy(cb.desc(cb.selectCase().
when(cb.isNull("field name"),0).otherwise(1)),
cb.asc("field name");
Updated
Error says:
ava.lang.String cannot be cast to com.test.test.classes.TblTaxType
what is happening is when I add the tag select distinct taxtcode error is appearing. But when I removed the select tag like FROM tblTaxType tbl_tax_type WHERE bfnsCode = ? everything is fine. What is the cause? this is my code:
String hql = "SELECT DISTINCT TAXT_CODE FROM tbl_tax_type WHERE BFNS_CODE = ?";
try {
setSession(HibernateUtil.getSession());
#SuppressWarnings("unchecked")
List <TblTaxType> resultList = getSession().createSQLQuery(hql)
.setString(0, bfnsCode)
.list();
Your entity is probably named TblTaxType, not tblTaxType. Case matters.
Side note: don't name sql an HQL query. SQL and HQL are different languages.
Solved it using GROUP BY instead by using DISTINCT.
String hql = "FROM TblTaxType tbl_tax_type WHERE bfnsCode = ? GROUP BY taxtCode";
Your query returns TAXT_CODE, this field is a property of your TblTaxType entity, so you can't cast one property (string) in your main entity. This is the reason of your error.
If you need complete entity you must change your query but DISTINCT is not useful in this case because if you extract complete entity, there's ID field (different for each row). If you want a first element, you can add in your query ORDER BY clause with LIMIT 1 (is MySql).
A solution with GROUP BY works only if you use MySql as DBMS because if you have Sql Server the correct behaviour of field list / group by is: a field in field list must be in GROUP BY cluse or must be in aggregate function.