Hibernate Projection returing result as Object - java

I want to write following sql using projection in hibernate
SELECT id, name, MAX(ver)
FROM bizterm
WHERE name ILIKE '%AB%'
GROUP BY name, id order by name asc
I have written following code
Session session=sessionFactory.getCurrentSession();
Criteria criteria=session.createCriteria(BizTerm.class);
criteria.add(Restrictions.ilike("name", searchString,MatchMode.ANYWHERE));
criteria.addOrder(Order.asc("name"));
ProjectionList projList=Projections.projectionList();
projList.add(Projections.max("ver"));
projList.add(Projections.groupProperty("id"));
projList.add(Projections.groupProperty("name"));
criteria.setProjection(projList);
In the table id,ver are the PKEY.
This query is running fine but in result I am getting value of only 3 column that is ver,id,name that too as Object,There are other column like status,level in the BizTerm table those value are not getting returned in the result set. How can I get those using projection? I tried projList.add(Projections.property("status")); but its not working.
I want this query to be executed
SELECT id, name,status,level MAX(ver)
FROM bizterm
WHERE name ILIKE '%AB%'
GROUP BY name, id order by name asc using projection in hibernate

Did like this..now its working no error
Criteria criteria=session.createCriteria(BizTerm.class);
criteria.add(Restrictions.ilike("bizTermName", searchString,MatchMode.ANYWHERE));
criteria.addOrder(Order.asc("bizTermName"));
ProjectionList projList=Projections.projectionList();
projList.add(Projections.max("bizTermversion"));
projList.add(Projections.groupProperty("bizTermId"));
projList.add(Projections.groupProperty("bizTermName"));
projList.add(Projections.max("status"));
projList.add(Projections.max("levels"));
projList.add(Projections.max("createDate"));
projList.add(Projections.max("modifyDate"));
Note: I dont need maximum of status,levels,createDate,modifyDate but if I am not writing them inside max function then getting following error
[Error Code: 0, SQL State: 42803] : column "levels" must appear in the GROUP BY clause or be used in an aggregate function
with max function everything seems to be fine

Related

Setting a collection parameter as a list for column values

I'm trying to write a query with a Collection parameter. It is assumed that query would turn this collection to a column of its values for the further operations. I'm using Spring, so now my query looks like:
#Query(value = "SELECT id FROM unnest(array[?1]) id", nativeQuery = true)
List<Object> getIds(Collection<String> ids);
It doesn't work, because Hibernate set collections as parameters in braces, so the real query will be send to DB:
SELECT id FROM unnest(array[('1', '2')]) id
This is not a valid query, the error is raising:
ERROR: a column definition list is required for functions returning
"record" SQL state: 42601
Right version of it must be:
SELECT id FROM unnest(array['1', '2']) id
So please can anybody tell me, if there is a way I could set a collection as query parameter without braces? Or maybe there is an another way to turn collection to column?

The column name is not valid - error

I am getting this error while I am fetching value from resultset.
Error : com.microsoft.sqlserver.jdbc.SQLServerException: The column name company.short_name is not valid
CASE 1 :
select company.short_Name,location_name from company,location;
this query is executing fine on SQL Server but in my java code when I trying to retrieve value like resultset.getString("company.short_name"); that time this give the above error.
CASE 2 :
select company.short_Name short_name,location_name from company,location;
and retrieve value like resultset.getString("short_name"); than it work fine with both database MySQL and MSSQL.
I am migrating my database from MySQL to MSSQL.above case 1 is work fine in MySQL, but why it is not work in MSSQL?
resultset.getString("company.short_name"); is wrong here. No need to specifying fully qualified name while trying to fetch the data in your application. Just specify the column name like resultset.getString("short_name");.
Cause even though you say select company.short_Name ... query out the column name as short_Name since that's what defined in table schema.
In case both tables has same column which may result in ambiguity, give a alias name to the columns like
select company.short_Name as company_shortname,
location.short_Name as location_shortname,
location.location_name from company,location;
add the following to your application.properties file
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
When you do
select company.short_Name,location_name from company,location;
This query outs the column name short_Name and resultSet would also have short_Name
since the company.short_name doesnt exist you get an error.
the function resultset.getString(String columnLabel)
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
Parameters:
columnLabel the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is null
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set
in the function resultset.getString(String columnLabel), the arg is a column name for executing sql, the statement select company.short_Name,location_name from company,location; will get a result set, which has table headers short_Name,location_name

Hibernate 2 with MSSQL for ORDER BY

I have been working with Oracle and Postgre and recently switched to MS SQL 2012.
I use hibernate in my application and wherever I have used the Order by Criteria:
(criteria.addOrder(Order.asc("applicationId")));
It causes an error saying:
aggregate functions dont work.
Once I comment that line out my program works and data can be retrieved.
I'm using Hibernate 3.
Is there any way to order it through hibernate without this error?
edit..
This is one error I get,
Column "SKY.tcrent.RENTNO" is invalid in the ORDER BY clause because
it is not contained in either an aggregate function or the GROUP BY
clause.
Edit 2..
MY query
Query tcSchaduleQ = getSession().createQuery("SELECT SUM(tcs.dueAmount) FROM TrialCalculationSchedule tcs WHERE tcs.facilityId=:facilityId AND tcs.rentalNumber>:rentalNumber AND tcs.dueDate>:dueDate AND dueTypeId IN(:dueTypeId) ORDER BY tcs.rentalNumber ").setInteger("rentalNumber", facility.getPeriod() - noOfprePayments).setInteger("facilityId",facility.getFacilityId()).setDate("dueDate", date).setParameterList("dueTypeId", plist);
Number tcsAmt = (Number) tcSchaduleQ.uniqueResult();
and this is what hibernate generates in HQL
SELECT
SUM(tcs.dueAmount)
FROM
TrialCalculationSchedule tcs
WHERE
tcs.facilityId=:facilityId
AND tcs.rentalNumber>:rentalNumber
AND tcs.dueDate>:dueDate
AND dueTypeId IN(
:dueTypeId
)
ORDER BY
tcs.rentalNumber
and this is the SQL
select
SUM(trialcalcu0_.DUEAMT) as col_0_0_
from
SKYBANKSLFHP.tcrent trialcalcu0_
where
trialcalcu0_.FACID=?
and trialcalcu0_.RENTNO>?
and trialcalcu0_.DUEDATE>?
and (
trialcalcu0_.DUETYPEID in (
? , ?
)
)
order by
trialcalcu0_.RENTNO
Look Like you mix aggregate and non-aggregate expressions .If you are using any aggregate function like AVG() in Select query with some other non-aggregate then you must use Group By ..
Try something like this
createQuery("SELECT SUM(tcs.dueAmount) As DueAmount ...
If you are using Criteria then it should be like this
Criteria crit = sess.createCriteria(Insurance.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.sum("investementAmount"));
crit.setProjection(proList);
List sumResult = crit.list();

HQL does not ignore values with blank string in column

I am trying to setup a query for my application to pull only values from a table that have a specific column set. Mostly this column will be null, but if you edit and save the item on the application end without putting anything in this field, then it saves a blank string to that database field.
I have tried the TSQL query:
SELECT * from TABLE where COLUMN is not NULL AND COLUMN != ''
This query returns the results I need, but when I run the same query in HQL:
SELECT OBJECT from TABLE where COLUMN is not NULL and COLUMN <> ''
Then it still contains the values that have a blank string in that column. I have tried this using HQL with the operators <> and !=, and have also tried converting it to a criteria object using Restrictions.ne("column","") but nothing seems to provide the result I need.
I tried Length as in the comments, but had no luck. With the length in the query hibernate generates the full query as so. the time_clock_id column is the one that i'm having the problem with. Hibernate is set to SQLServerDialect
select timezone0_.time_zone_id as time1_368_, timezone0_.version as version368_, timezone0_.modification_timestamp as modifica3_368_, timezone0_.time_offset as time4_368_, timezone0_.modification_user as modifica5_368_, timezone0_.name as name368_, timezone0_.description as descript7_368_, timezone0_.active as active368_, timezone0_.time_clock_id as time9_368_ from time_zone timezone0_ where timezone0_.active=1 and (timezone0_.time_clock_id is not null) and len(timezone0_.time_clock_id)>0
Rookie Mistake. There was another place within my action class where I was using a different query to build the select list in the application. This was resulting in the list being overwritten with all values instead of those that use blank. After snipping this duplication I can use the operator column <> '' and I am getting the correct results

Problem with processing count column with Hibernate

I want to process the count column in my action how to do with help of hiberante.in my application every class is mapped to every table here I'm using billing table. In billing table details and other columns are there.
If i pass the query into execute sql query method it getting all the details, but it returns the count column as that corresponding dao class. How to process that column. Here is my query.
select u,b,b,count(b.details) from com.cod.model.Billing b,com.cod.model.User u where b.accountId=u.id and b.details not like '%Monthly Package With Usage Value Rs:0.0%' and b.details not like '%A/C Opened:%' and b.details not like '%Voucher Recharged%' and b.details not like '%default0%' group by u.username,b.details
Here it's getting user and billing table values but count column also comes as billing table object.
Don't make the results list type safe or hibernate will grab everything he can and push it in an instance of that object. When you make your results list not type safe hibernate will just return an List over which you can iterate and retrieve the fields you need.
List.get(0)[3] should result in you having your count.
String hql = "...";
Query query = session.createQuery(hql);
//List< com.cod.model.Billing> results = query.list();
List results = query.list();

Categories