My question is rather simple: I have this query:
SELECT * FROM TABLE t WHERE
(SELECT count(*) FROM TABLE tbis WHERE TRUNC(t.date) = TRUNC(tbis.date))>1 ;
the field date is a timestamp.
How do I do that with the criteria API?
I have something like this (trunc() is valid with my db server, the sql request works.):
Criteria crit = session.createCriteria(Myclass.class, "t");
crit.createAlias("t.date", "dateT");
DetachedCriteria subcrit = DetachedCriteria.forclass(MyClass.class, "tbis");
subcrit.createAlias("tbis.date", "dateTbis");
subcrit.add(Restrictions.sqlRestriction("TRUNC(dateT) = TRUNC(dateTbis)"));
subcrit.setProjection(Projections.count("id"));
crit .add(Subqueries.gt(1, subcrit));
return crit.list();
Somehow in the log, i got:
org.hibernate.QueryException: not an association: date
I tried various things, but couldn't get it to work...
I tried:
Criteria crit = session.createCriteria(Myclass.class, "t");
DetachedCriteria subcrit = DetachedCriteria.forclass(MyClass.class, "tbis");
subcrit.add(Restrictions.sqlRestriction("TRUNC(t.date) = TRUNC(tbis.date)"));
subcrit.setProjection(Projections.count("id"));
crit .add(Subqueries.gt(1, subcrit));
return crit.list();
and the SQL condition generated was:
TRUNC(t.date) = TRUNC(tbis.date))
with the log:
18:34:04,461 WARN [JDBCExceptionReporter] SQL Error: 904, SQLState: 42000
18:34:04,461 ERROR [JDBCExceptionReporter] ORA-00904: "T"."DATE": invalid identifier
18:34:04,461 WARN [CriteriaAdapter] list exception:
org.hibernate.exception.SQLGrammarException: could not execute query
Also
Criteria crit = session.createCriteria(Myclass.class, "t");
DetachedCriteria subcrit = DetachedCriteria.forclass(MyClass.class, "tbis");
subcrit.add(Restrictions.sqlRestriction("TRUNC({t}.date) = TRUNC({tbis}.date)"));
subcrit.setProjection(Projections.count("id"));
crit .add(Subqueries.gt(1, subcrit));
return crit.list();
with the condition becoming:
TRUNC({t}.date) = TRUNC({tbis}.date))
and the logs:
18:36:28,206 WARN [TxConnectionManager] Connection error occured: org.jboss.resource.connectionmanager.TxConnectionManager$TxConnectionEventListener#1b3febd3[state=NORMAL mc=org.jboss.resource.adapter.jdbc.xa.XAManagedConnection#4cb16baf handles=1 lastUse=1343284588160 permit=true trackByTx=true mcp=org.jboss.resource.connectionmanager.JBossManagedConnectionPool$OnePool#7f16f514 context=org.jboss.resource.connectionmanager.InternalManagedConnectionPool#3c34353b xaResource=org.jboss.resource.adapter.jdbc.xa.XAManagedConnection#4cb16baf txSync=null]
java.lang.NullPointerException
at oracle.jdbc.driver.T4C8Oall.getNumRows(T4C8Oall.java:1153)
[...]
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
Or even:
Criteria crit = session.createCriteria(Myclass.class, "t");
DetachedCriteria subcrit = DetachedCriteria.forclass(MyClass.class, "tbis");
subcrit.add(Restrictions.sqlRestriction("TRUNC({t.date}) = TRUNC({tbis.date})"));
subcrit.setProjection(Projections.count("id"));
crit .add(Subqueries.gt(1, subcrit));
return crit.list();
With the same result as previously.
I think criteria is unable to detect the alias of the subquery... But I have to access that value, any workaround?
First you can try if you shouldn't put the { } only around the alias in the sqlRestriction :
subcrit.add(Restrictions.sqlRestriction("TRUNC({t}.date) = TRUNC({tbis}.date)"));
If you don't want to compare a part of the date fields (like the days), but want to see if the entire date fields are equal, you can just let Hibernate do the comparison like this:
Restrictions.eq(t.date, tbis.date)
If you want to compare a part of a date field, I refer you to this question.
Related
I am writing a util function to get the total record count based on any HQL that I get passed in without loading all data. The passed in HQL might be pretty complex with lots of selects, joins, where conditions, groupings and sortings. For that I want to wrap the query with a SELECT COUNT(*) FROM (<ORIGINAL_QUERY>) x. I found out, that this is not possible with HQL, because Hibernate does not allow subqueries in FROM elements.
Now, I am trying to translate this random HQL query which might have some named parameters (some of them might be simple parameters, some might be lists) to an executable SQL statement without inlining the parameter values. This seems to work with simple parameters, but does not work with list parameters.
The hqlString and the namedParameterMap comes from somewhere outside:
final String hqlString = "...";
final Map<String, Object> namedParametersMap = ...;
Code to translate HQL to SQL (and ParameterTranslations:
final QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
final SessionFactoryImplementor factory = getSessionFactory();
final QueryTranslator translator = translatorFactory.createQueryTranslator(hqlString, hqlString, Collections.EMPTY_MAP, factory, null);
translator.compile(Collections.EMPTY_MAP, false);
final String sqlString = translator.getSQLString();
final ParameterTranslations parameterTranslations = translator.getParameterTranslations());
Code to create a SQLQuery, set the Parameters and execute the Query:
SQLQuery sqlQuery = getCurrentSession().createSQLQuery(sqlString);
((Set<?>) parameterTranslations.getNamedParameterNames()).forEach(parameterName -> {
for (int position : parameterTranslations.getNamedParameterSqlLocations(parameterName)) {
sqlQuery.setParameter(position, namedParametersMap.get(parameterName));
}
});
final Long rowCount = ((BigInteger) query.uniqueResult()).longValueExact();
This query works an expected:
final String hqlString = "SELECT p.firstname, p.surname FROM Person p WHERE p.id = :param1";
final Map<String, Object> namedParametersMap = Maps.newHashMap(ImmutableMap.<String, Object>of("param1", Integer.valueOf(1));
This query does not work:
String hqlString = "SELECT p.firstname, p.surname FROM Person p WHERE p.id IN (:param1)";
final Map<String, Object> namedParametersMap = Maps.newHashMap(ImmutableMap.<String, Object>of("param1", Lists.newArrayList(Integer.valueOf(1)));
Exception:
org.hibernate.exception.SQLGrammarException: could not extract ResultSet at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79) at org.hibernate.loader.Loader.getResultSet(Loader.java:2313) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2096) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2072) at org.hibernate.loader.Loader.doQuery(Loader.java:941) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:352) at org.hibernate.loader.Loader.doList(Loader.java:2813) at org.hibernate.loader.Loader.doList(Loader.java:2796) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2625) at org.hibernate.loader.Loader.list(Loader.java:2620) at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:322) at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1996) at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322) at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125) at org.hibernate.internal.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:966) at HQLQueryUtils.getCount(HQLQueryUtils.java:350)
Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: integer = bytea HINT: No operator matches the given name and argument type(s).
You might need to add explicit type casts. Position: 301 at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2433) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2178) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:306) at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441) at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365) at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:155) at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:118) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70) ... 49 more
Environment:
Java 8
Hibernate 5.1.8
Postgres-JDBC 42.2.2
PostgreSQL Server 10.5
In HQL you can use query parameter and set Collection with setParameterList method.
Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
q.setParameterList("names", names);
You can use direct sql
String sql="your query"
Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
query.setParameter("paramterName", parameterValue);
List<Object[]> resultSet = query.list();
List<YouClass > data= new ArrayList<>();
for (Object[] row : resultSet) {
YouClass yourObject=new YouClass ();
yourObject.setDate((Date) row[0]);
yourObject.setAmount((BigDecimal) row[1]);
data.add(yourObject);
}
Suppose Yourclass has two element date and amount
i am trying to fetch the id of last column in descending order.
the query which returns last column is
select id from(select id from challan
order by id desc) where ROWNUM=1;
now i am trying to do same thing using hibernate.
public long getIdOnChallanTable() {
session = sessionFactory.openSession();
trans = session.beginTransaction();
Query<Object[]> query = session.createNativeQuery("select id
from(select id from challan order by id desc) where ROWNUM=1;");
Long value = 0L;
List<Object[]> list = query.getResultList();
for ( Object lst : list){
Object[] objects =(Object[]) lst;
value=(Long)(objects[0]);
}
return value;
}
and the error is:
2017-07-26 12:37:36 [http-nio-7080-exec-1] WARN :: SQL Error: 911, SQLState: 22019
2017-07-26 12:37:36 [http-nio-7080-exec-1] ERROR:: ORA-00911: invalid character
update error javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
You don't need the semicolon at the end of the query and please use proper whitespacing. In the FROM clause, you don't have the whitespace between the subquery and the FROM keyword.
Note: don't forget to commit/rollback the transaction at the end and handle the exceptions as well. I hope this was just a sketch to show us the problem and not a code from a real world application.
I want to build a query like below using Hibernate Projections attribute. Can someone check the below. I have written java code like.
DetachedCriteria dCriteria = DetachedCriteria.forClass(FinancialYearQuater.class, "FinancialYearQuater");
dCriteria.add(Restrictions.eq("FinancialYearQuater.finYear", year));
dCriteria.addOrder(Order.asc("finYear"));
dCriteria.setResultTransformer(Projections.distinct(Projections.property("id")));
List<FinancialYearQuater> list = (List<FinancialYearQuater>) findAll(dCriteria);
Here's the SQL query:
select
distinct
this_.FINY_NAME,
this_.FINY_YEAR,
this_.QTR_NAME,
this_.QTR_NO,
this_.QTR_PERIOD
from
V_FINYR_QTR this_
where
this_.FINY_YEAR=2016
order by
this_.FINY_YEAR asc
I have written below code. Is that the correct way get the distinct data?
DetachedCriteria dCriteria = DetachedCriteria.forClass(FinancialYearQuater.class, "FinancialYearQuater");
dCriteria.add(Restrictions.eq("FinancialYearQuater.finYear", year));
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("FinancialYearQuater.finYear"), "finYear");
projList.add(Projections.property("FinancialYearQuater.finYearName"), "finYearName");
projList.add(Projections.property("FinancialYearQuater.qtrNo"), "qtrNo");
projList.add(Projections.property("FinancialYearQuater.qtrPeriod"), "qtrPeriod");
dCriteria.setProjection(Projections.distinct(projList));
dCriteria.addOrder(Order.asc("finYear"));
List<FinancialYearQuater> list = (List<FinancialYearQuater>) findAll(dCriteria);
I've written this in sql server:
select max(processed_trans_id) from EQUITY_TRANSACTION where transaction_date <= '2016-06-22' and company_id=75 group by comp_acct_id
But when I try to write the same in Hibernate Criteria, like this:
DetachedCriteria dCriteria = DetachedCriteria.forClass(EquityTransaction.class)
.add(Restrictions.eq("clientCompany.id", sb.getClientCompany().getId()))
.add(Restrictions.le("transactionDate", sb.getQualifyDate()))
.setProjection(Projections.projectionList()
.add(Projections.max("processedTransaction.id"), "processedTransaction.id")
.add(Projections.groupProperty("holderCompanyAccount.id")));
I get this as the sql query from hibernate:
select max(processed_trans_id), comp_acct_id from EQUITY_TRANSACTION where transaction_date <= '2016-06-22' and company_id=75 group by comp_acct_id
How do I replicate the original SQL query in Hibernate criteria?
I was able to resolve this using the following query. Worked like a charm!
DetachedCriteria dCriteriaEt1 = DetachedCriteria.forClass(EquityTransaction.class, "et1")
.add(Restrictions.eq("clientCompany.id", decldDvd.getClientCompany().getId()))
.add(Restrictions.le("transactionDate", decldDvd.getQualifyDate()))
.setProjection(Projections.projectionList()
.add(Projections.max("processedTransaction.id"), "processedTransaction.id"))
.add(Restrictions.eqProperty("et1.holderCompanyAccount.id", "et2.holderCompanyAccount.id"));
logger.info("Retrieving all qualified company account balances...");
Criteria getQualifiedBalances = dao.getSession().createCriteria(EquityTransaction.class, "et2")
.add(Subqueries.propertyIn("processedTransaction.id", dCriteriaEt1))
.add(Restrictions.gt("balance", 0l))
.setProjection(Projections.projectionList()
.add(Projections.property("holderCompanyAccount.id"),"holderCompanyAccount.id")
.add(Projections.property("balance"), "balance"))
.addOrder(Order.asc("holderCompanyAccount.id"))
.addOrder(Order.desc("processedTransaction.id"))
.setResultTransformer(new AliasToBeanNestedResultTransformer(EquityTransaction.class));
I'm trying to reproduce a SQL query containing self-joins using Hibernate. This is the SQL:
select cur.*
from first ft1,
first ft2,
second sc1,
second sc2,
third thd
where sc1.id = sc2.id
and sc1.idFirst = ft1.id
and sc2.idFirst = ft2.id
and ft1.is <> ft2.id
and ft1.id = thd.idFirst
and ft2.id = ?
I've tried using Criteria and DetachedCriteria as follows, by I'm not able to get it to work:
Criteria criteria = this.getSession().createCriteria(Third.class);
DetachedCriteria first1Criteria = DetachedCriteria.forClass(First.class);
first1Criteria.setProjection(Projections.property("id"));
DetachedCriteria first2Criteria = DetachedCriteria.forClass(First.class);
first2Criteria.setProjection(Projections.property("id"));
first2Criteria.add(Restrictions.eq("id", id)); // where id is passed in from the calling method
first2Criteria.getExecutableCriteria(getSession()).list();
DetachedCriteria second1Criteria = DetachedCriteria.forClass(Second.class);
second1Criteria.setProjection(Projections.property("id"));
DetachedCriteria second2Criteria = DetachedCriteria.forClass(Second.class);
second2Criteria.setProjection(Projections.property("id"));
second1Criteria.add(Property.forName("id.id").in(second2Criteria ));
second1Criteria.add(Property.forName("id.idFirst").in(first1Criteria));
second1Criteria.add(Property.forName("id.idFirst").in(first2Criteria));
first1Criteria.add(Property.forName("id").notIn(first2Criteria));
criteria.add(Property.forName("id").in(first1Criteria));
return criteria.list();
No exceptions are thrown in this case, but the query isn't actually executed. I've tried a few differnt combinations along these lines, but unsuccessfully. Any help is much apreciated!