Writing sql query in hibernate - java

I have a sql query:
select COUNT (distinct agentG) as count from Test_CPView where kNum = ‘test k1’ and pName = ‘test p1’
I'm trying to write into criteria query but it hasn't worked for me:
statelessSession = sessionFactory.openStatelessSession();
Criteria crit = statelessSession.createCriteria(APRecord.class, "apr");
ProjectionList projList = Projections.projectionList();
projList.add(Projections.groupProperty("pName"));
projList.add(Projections.groupProperty("kNum"));
projList.add(Projections.countDistinct("agentG"));
crit.setProjection(projList);
This produces:
Hibernate: select this_.pName as y0_, this_.kNum as y1_, count(distinct this_.agentG) as y2_ from Test_CPView this_ where (lower(this_. pName + '~' + this_. kNum) like ? or lower(this_. pName + '~' + this_. kNum) like ? or lower(this_. pName + '~' + this_. kNum) like ? or lower(this_. pName + '~' + this_. kNum) like ?) group by this_.pName, this_. kNum
and the return results are null.
How can I convert the above sql query into hibernate?

Session.createCriteria from Docs
You have not added Restrictions
statelessSession = sessionFactory.openStatelessSession();
Criteria crit = statelessSession.createCriteria(APRecord.class, "apr");
crit .add(Restrictions.eq("kNum", "test k1"));
crit .add(Restrictions.eq("pName ", "test k1"));
crit.setProjection(Projections.countDistinct("agentG"));
Integer count = crit.uniqueResult();

statelessSession = sessionFactory.openStatelessSession();
Criteria crit = statelessSession.createCriteria(APRecord.class, "apr");
crit.add(Expression.eq("kNum","test k1"));
crit.add(Expression.eq("pName","test p1"));
crit.setProjection(Projections.countDistinct("agentG"));

Query query = session.createQuery("count(agentG) from APRecord where kNum = :kNum and pName = :pName");
query.setParameter("kNum", "test k1");
query.setParameter("pName", "test p1");
return (Integer) query.uniqueResult();

Related

How to use ilike and % in createSQLQuery in hibernate java

I have made a sql query now i need to add search from it. it needs to search from userfullname the given keyword query is working in postgresql but it is not working with CreateSqlQuery.
sqlQuery = "select * from ( " + sqlQuery + ") a where a.payeeName ilike :searchpayeename ";
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery)
.addScalar("id", new LongType());
query.setParameter("searchpayeename", "%"+payee + "%");
It is not giving me result while if i run same query in sql it is giving result. Any Idea.
Operator iLike not work with jpql, only with native query.
If you want use jpql you need simulate the iLike function using toLowerCase() on both sides of query.
jpqlQuery = "SELECT a FROM EntityName a WHERE LOWER(a.payeeName) LIKE :searchpayeename";
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(jpqlQuery)
.addScalar("id", new LongType());
query.setParameter("searchpayeename", "%" + payee.toLowerCase() + "%");
Or using createNativeQuery:
sqlQuery = "SELECT * FROM EntityName a WHERE " +
"LOWER(a.payeeName) LIKE LOWER(CONCAT('%',:searchpayeename, '%'))";
SQLQuery query = sessionFactory.getCurrentSession().createNativeQuery(sqlQuery)
.addScalar("id", new LongType());
query.setParameter("searchpayeename", "%" + payee.toLowerCase() + "%");

Hibernate Criteria uniqueResult

My sql query is somethin like below
SELECT count(1),tran_nbr FROM AAA WHERE P_D IN (3,4) AND
DTE_OF_ISS BETWEEN to_date('01/01/2014','mm/dd/yyyy') and to_date('01/31/2015' ,'mm/dd/yyyy')
And i have written a hibernate query like this.
Criteria criteria = session.createCriteria(AAA.class).setProjection(Projections.rowCount());
criteria.add(Restrictions.sqlRestriction("(P_D IN ('4'))"));
if (reportsForm.getFromDate() != null && reportsForm.getToDate() != null) {
criteria.add(Restrictions.sqlRestriction("DTE_OF_ISS = to_date('"+ utils.convertDateToString(reportsForm.getFromDate()) + "', 'MM/dd/yyyy')"));
criteria.add(Restrictions.sqlRestriction("DTE_OF_ISS <= to_date('"+ utils.convertDateToString(reportsForm.getToDate()) + "', 'MM/dd/yyyy')"));
}
criteria.setFetchSize(100);
criteria.setMaxResults(500);
listResult = criteria.list();
listResult = criteria.list();
int count = ((Long) criteria.uniqueResult()).intValue();
when i see the "show_sql" the query looks like this.
select * from ( select count(*) as y0_ from Schema.AAA this_ where (P_D IN ('4')) and DTE_OF_ISS = to_date('01/01/2014', 'MM/dd/yyyy') and DTE_OF_ISS <= to_date('01/31/2015', 'MM/dd/yyyy') ) where rownum <= ?
No idea from where the addition select coming and rownum? Please help me out..

How do I create my query with Hibernate Criteria

I have to create the following query with Criteria:
SELECT r.*,(
SELECT COUNT(*) FROM APP.P_FORM_QUESTION_ANSWER qa
WHERE qa.J_STATUS = 'CORRECT'
AND qa.J_FORM_ID = r.J_FORM_ID AND qa.J_AUTHOR_ID = r.J_AUTHOR_ID
AND qa.J_FORM_RESULT_ID = r.J_ROW_ID
) as correctCount
FROM APP.P_FORM_RESULT r
WHERE r.J_FORM_ID = '123456'
ORDER BY correctCount DESC;
I try to use DetachedCriteria for extra column, but I do not see how to represent :
"qa.J_FORM_ID = r.J_FORM_ID AND qa.J_AUTHOR_ID = r.J_AUTHOR_ID
AND qa.J_FORM_RESULT_ID = r.J_ROW_ID"
in the DetachedCriteria, and add my DetachedCriteria as a new column
Criteria criteria =
HibernateUtil.getSession().createCriteria(FormResult.class, "formResult");
criteria.add(Restrictions.eq("formResult.formId", formId));
DetachedCriteria correctCount =
DetachedCriteria.forClass(QuestionAnswer.class, "questionAnswer");
correctCount.add(
Restrictions.eq("questionAnswer.status",QuestionAnswerStatus.CORRECT));
// How to retrieve 'formResult' ?
correctCount.add(Restrictions.eq("questionAnswer.formId", "formResult.formId"));
// How to retrieve 'formResult' ?
correctCount.add(Restrictions.eq("questionAnswer.authorId", "formResult.authorId"));
// How to retrieve 'formResult' ?
correctCount.add(
Restrictions.eq("questionAnswer.formResult.rowId", "formResult.rowId"));
correctCount.setProjection(Projections.rowCount());
// How to add my DetachedCriteria as a new column
criteria.setProjection(Projections.alias(correctCount, "correctCount"));
The Lines with comments are the lines for which I cannot find the solution.
Finally, I created a different SQL query that gives me the same result:
SELECT r.J_ROW_ID, COUNT(DISTINCT qa.J_ROW_ID) as correctCount
FROM APP.P_FORM_RESULT r left join APP.P_FORM_QUESTION_ANSWER qa on qa.J_FORM_ID = r.J_FORM_ID AND qa.J_AUTHOR_ID = r.J_AUTHOR_ID AND qa.J_FORM_RESULT_ID = r.J_ROW_ID AND qa.J_STATUS = 'CORRECT'
WHERE r.J_FORM_ID = '123456'
GROUP BY r.J_ROW_ID
ORDER BY correctCount DESC;
And I used HQL because I cannot find how to do it in Criteria:
// HQL Query to retrieve the list of FormResult IDs
StringBuilder hql = new StringBuilder();
hql.append("SELECT r.id");
hql.append(" FROM QuestionAnswer qa RIGHT JOIN qa.formResult as r");
hql.append(" WHERE r.formId = :formId AND (qa.status = :status OR qa.status IS NULL)");
hql.append(" GROUP BY r.id");
hql.append(" ORDER BY COUNT(DISTINCT qa.id) DESC"));
Query query = HibernateUtil.getSession().createQuery(hql.toString());
query.setParameter("formId", formId);
query.setParameter("status", QuestionAnswerStatus.CORRECT);
// Retrieve the list of FormResult objects from the list of IDs previously retrieved
List<Long> result = query.list();
if (result != null && !result.isEmpty()) {
for (Long resultId : result) {
formResults.add(getData(FormResult.class, resultId));
}
}
The downside is that I have to retrieve each FormResult one by one from my list of IDs retrieved by my HQL query

Converting HQL to Criteria

HQL I want to convert in the Criteria.
HQL
select com from News as news " +
"join news.comments as com " +
"where news.id = :id " +
"order by com.addDate desc"
Criteria
DetachedCriteria criteria = DetachedCriteria.forClass(News.class);
criteria.add(Restrictions.idEq(id));
DetachedCriteria cComment = criteria.createCriteria("comments");
cComment.addOrder(Order.desc("addDate"));
List<Comment> list = (List<Comment>)findByCriteria(cComment, false);
Criteria is working, but returned list News. I want to return the Сomments. Please help me?
try this may help you:
DetachedCriteria criteria = DetachedCriteria.forClass(News.class);
criteria.setProjection( Projections.property("com"), "com"));
criteria.add(Restrictions.idEq(id));
DetachedCriteria cComment = criteria.createCriteria("comments");
cComment.addOrder(Order.desc("addDate"));
List<String> list = (List<String>)findByCriteria(cComment, false);

Why SQLQuery setParameter cannot use LIKE?

I have here:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME LIKE '%?%'");
query.setParameter(0, personName);
I get the following error:
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
But when I try:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME = ?");
query.setParameter(0, personName);
its working.
I need to use LIKE.
You can do like this:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME LIKE ?");
query.setParameter(0, "%" + personName + "%");
User criteria as
Criteria criteria = getSession().createCriteria(Person.class);
criteria.add(Restrictions.like("name", personName, MatchMode.ANYWHERE));
criteria.list();
String strQuery = "SELECT * FROM PERSON WHERE upper(NAME) LIKE '%"
+ personName.trim().toUpperCase() + "%'";
Session session = getSession();
SQLQuery query = session.createSQLQuery(strQuery );

Categories