Hibernate Criteria uniqueResult - java

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..

Related

Conditional AND using hibernate

I have the following query:
#NamedQuery(name = "User.findByParams", query=
"SELECT *
FROM User user
WHERE user.name type = :inputType")
And I wish to add AND statement, that will take place only if the inputs are supplied:
#NamedQuery(name = "User.findByParams", query=
"SELECT *
FROM User user
WHERE user.name type = :inputType AND (:ageInput != null AND user.age > :ageInput")
It means that if the ageInput is supplied, filter by it as well. If not- ignore this param. Any ideas?
Any ideas?
As the previous speakers wrote, you can use Criteria
Criteria criteria = createCriteria()
.add(Restrictions.eq("type", type));
if (ageInput != null) {
criteria.add(Restrictions.eq("ageInput", ageInput));
}
List<User> list = criteria.list();
or SQLQuery
String sql = "SELECT * " +
"FROM User user " +
"WHERE user.type = :inputType ";
sql += (ageInput != null) ? "AND ageInput = :ageInput " : "";
Query query = sessionFactory.getCurrentSession().createSQLQuery(sql)
.setParameter("inputType", inputType);
if(ageInput != null) {
query.setParameter("ageInput", ageInput);
}
return (List<User>) query.list();
You will have to check if ageInput is supplied or not in code and will have to call different methods accordingly.
Means if ageInput is supplied then you will have to call a method having ageInput constraint o/w call method which do not have ageInput constraint.
Alternatively, you can use predicates and execute a query.

Querying through java

I have two tables: harvested_record and harvested_record_simple_keys there are in relation one-to-one.
harvested_record
id|harvested_record_simple_keys_id|a lot of columns
harvested_record_simple_keys
id| a lot of columns
and I want to make a query in which I need to join there two tables. As a result I will have a table:
joined_table
id(harvested_record)| (harvested_record_simple_keys)|a lot of columns.
Unfortunately I get an exception: nested exception is java.sql.SQLSyntaxErrorException: Column name 'ID' matches more than one result column.
I've understood this is because after join I will have two columns 'id'. Does anyone can help me with solution?
P.S.
SQL statement(works in IDEA console):
SELECT * FROM ( SELECT TMP_ORDERED.*, ROW_NUMBER() OVER () AS ROW_NUMBER FROM (SELECT * FROM harvested_record hr JOIN harvested_record_simple_keys hrsk ON hrsk.id = hr.harvested_record_simple_keys_id WHERE import_conf_id = ? ) AS TMP_ORDERED) AS TMP_SUB WHERE TMP_SUB.ROW_NUMBER <= 2 ORDER BY import_conf_id ASC, record_id ASC;
Java code(suppose error is here):
JdbcPagingItemReader<HarvestedRecord> reader = new JdbcPagingItemReader<HarvestedRecord>();
SqlPagingQueryProviderFactoryBean pqpf = new SqlPagingQueryProviderFactoryBean();
pqpf.setDataSource(dataSource);
pqpf.setSelectClause("SELECT *");
pqpf.setFromClause("FROM harvested_record hr JOIN harvested_record_simple_keys hrsk ON hrsk.id = hr.harvested_record_simple_keys_id");
String whereClause = "WHERE import_conf_id = :configId";
if (from!=null) {
fromStamp = new Timestamp(from.getTime());
whereClause += " AND updated >= :from";
}
if (to!=null) {
toStamp = new Timestamp(to.getTime());
whereClause += " AND updated <= :to";
}
if (configId != null) {
pqpf.setWhereClause(whereClause);
}
pqpf.setSortKeys(ImmutableMap.of("import_conf_id",
Order.ASCENDING, "record_id", Order.ASCENDING));
reader.setRowMapper(harvestedRecordRowMapper);
reader.setPageSize(PAGE_SIZE);
reader.setQueryProvider(pqpf.getObject());
reader.setDataSource(dataSource);
if (configId != null) {
Map<String, Object> parameterValues = new HashMap<String, Object>();
parameterValues.put("configId", configId);
parameterValues.put("from", fromStamp );
parameterValues.put("to", toStamp);
reader.setParameterValues(parameterValues);
}
reader.afterPropertiesSet();
Thank you in advance.
If you name your columns in the select statement instead of using 'SELECT *', you can omit the ID from one of the tables since it is always equal to the id from the other table.

Writing sql query in hibernate

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();

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

Hibernate DetachedCriteria Query with and clause in subselect

How can I solve this query with Hibernate's detached criteria? The hardest part for me is to bring the and u1.abrechnungsDatum is null into the subselect.
I want a query like this:
select *
from
patient as p
where
p.krankenstand = ?
and
? < ( select count(*) from ueberweisung u1 where p.id = u1.patient_id
and u1.abrechnungsDatum is null)
I have tried it with this
DetachedCriteria dc = DetachedCriteria.forClass(Patient.class, "patient");
dc.add(Restrictions.eq("krankenstand", true));
DetachedCriteria nab = dc.createCriteria("ueberweisungs", "nab");
nab.add(Restrictions.isNull("nab.abrechnungsDatum"));
dc.add(Restrictions.sizeGt("ueberweisungs", 0));
which gives me the following SQL-Statement
select
*
from
patient this_
inner join
ueberweisung nab1_
on this_.id=nab1_.patient_id
where
this_.krankenstand=?
and nab1_.abrechnungsDatum is null
and ? < (
select
count(*)
from
ueberweisung
where
this_.id=patient_id
)
As you can see, the and-clause for the field abrechnungsDatum is not inside the subselect. How can I achieve to get this inside?
Try this instead:
DetachedCriteria dc = DetachedCriteria.forClass(Patient.class, "patient");
dc.add(Restrictions.eq("krankenstand", true));
DetachedCriteria subquery = DetachedCriteria.forClass(Ueberweisung.class);
subquery.add(Restrictions.isNull("abrechnungsDatum"));
dc.add(Subqueries.ltAll(0, subquery));

Categories