Nested query with Hibernate HQL - mysql

Please I want to include a nested select from in a hql query like this:
Query query1 = session.createQuery("from Component where ( AC_ID IS NULL) AND ( WIP_ID IS NOT NULL ) AND ( SELECT USER_ID FROM WorkInProcess WHERE WIP_ID = 'WIP_ID' IS NULL) ");
How could I achieve this with hibernate hql query.
Thank you

With minimal information given i would say there are two classes Component.class and WorkInProcess.class. I guess WIP_ID is foreign key for WorkInProcess.class. You can use the following hql query or detached criteria based query to achieve it:
session.createQuery("from Component m where m.AC_ID is NULL and WIP_ID IS NOT NULL and m.USER_ID IN (" +
"select e.USER_ID from WorkInProcess e where e.WIP_ID:=wip_id) is null").setParameter("wip_id", wip_id).uniqueResult();
or
DetachedCriteria Query1 = DetachedCriteria.forClass(WorkInProcess.class);
Query1.add(Restrictions.eq("WIP_ID", WIP_ID));
Criteria Query2 = session.createCriteria(Component.class);
Query2.add(Restrictions.isNull("AC_ID"));
Query2.add(Restrictions.isNotNull("WIP_ID"));
Query2.add(Property.forName("USER_ID").eq(Query1));
Please refer : hql-and-nested-queries

Related

mysql use case in jpa query

I am building an endpoint where 3 query param comes in request like
status(mendatory)
searchCriteria(optional)
startDate(optional)
I am considering that i have to write three(3) native sql queries with combination of ex.
1: status and searchCriteria
2: status and startDate
3: status and searchCriteria and startDate
but I do not want to write three queries,
I know it is possible to achieve in a single query using case .
This is my native sql query
#Query(value = "select * from email_info u where u.status =:status and u.campaign =:searchCriteria and u.scheduleat =:startDate",
nativeQuery = true)
object getPromotional(String status, String searchCriteria, String startDate);
How to use case in above query using jpa like
CASE
WHEN :searchCriteria != null THEN u.campaign =:searchCriteria
WHEN :startDate != null THEN u.scheduleat =:startDate
END

Spring Data JPQL How to create a query with dynamic where clause?

I'm creating custom JPQL queries to fetch some data.
I have certain cases where I would like to add a where clause depending on if the parameter value is non null.
For example equivalent sql query:
//If parameter status is not null.
SELECT sum(A.sal) FROM TABLE A WHERE A.STATUS = 'X' GROUP BY A.CURRENCY;
//else
SELECT sum(A.sal) FROM TABLE A GROUP BY A.CURRENCY;
Can someone help me with it.
The two queries:
//If parameter status is not null.
SELECT sum(A.sal) FROM TABLE A WHERE A.STATUS = 'X' GROUP BY A.CURRENCY;
//else
SELECT sum(A.sal) FROM TABLE A GROUP BY A.CURRENCY;
can be compacted to one.
First lets declare a named parameter statusParam. This param can take any value (like 'X' or null from above). So the two queries above can be re-written to:
SELECT sum(A.sal) FROM A WHERE (A.STATUS = :statusParam OR :statusParam is null ) GROUP BY A.CURRENCY;
Come on, JPQL is just normal String :)
You want something like this?
private String generateHql(String status) {
String jpql = "SELECT sum(A.sal) FROM TABLE A ";
if (null != status) {
jpql += "WHERE A.STATUS = " +status ;
}
jpql += " GROUP BY A.CURRENCY "
return jpql;
}

Sql Alchemy filter / where clause joined by OR not AND

I want to select a bunch distinct records based off a composite key. In SQL I'd write something like this:
SELECT * FROM security WHERE (
exchange_code = 'exchange_code_1' AND code = 'code_1')
OR (exchange_code = 'exchange_code_2' AND code = 'code_2')
...
OR (exchange_code = 'exchange_code_N' AND code = 'code_N')
)
With SQLAlchemy I'd like to use the filter clause like:
query = sess.query(Security)
[query.filter(
and_(Security.exchange_code == security.exchange_code,
Security.code == security.code)
) for security in securities]
result = query.all()
The problem is filter and where join clauses with an AND not an OR... is there some way to use filter with OR?
Or is my only choice to generate a bunch of individual select's and UNION them? Something like:
first = exchanges.pop()
query = reduce(lambda query, exchange: query.union(exchange.pk_query),
first.pk_query())
query.all()
Use or_:
query = sess.query(Security).filter(
or_(*(and_(Security.exchange_code == security.exchange_code,
Security.code == security.code)
for security in securities)))
If your database supports it, you should use tuple_ instead.

HQL Query fails in Hibernate MySQL

I want to recuperate all rows from user table.
String queryS = "select u from user u";
System.out.println("entityManager: "+(entityManager == null));
Query query = entityManager.createQuery(queryS);
//staff
The line that throws the exception is Query query = entityManager.createQuery(queryS);
I don't know why even persistance file is ok and the table exists
The stack is:
10:36:06.693 [AWT-EventQueue-0] DEBUG org.hibernate.hql.ast.ErrorCounter - throwQueryException() : no errors
10:36:06.693 [AWT-EventQueue-0] DEBUG o.h.hql.antlr.HqlSqlBaseWalker - select << begin [level=1, statement=select]
You have to put the name of the table in the query as in the persistence file not in database.
If this:
String queryS = "select u from user u"
Is referred on table name you can't use createQuery method but createNativeQuery
If you want to use createQuery you must use in your query the entity/class mapped youe user table
Summarizing:
Case 1 (use createNativeQuery)
String queryS = "select u from user u";
Query query = entityManager.createNativeQuery(queryS);
Case 2 (use createQuery)
String queryS = "select u from " + User.class.getName() + " u";
Query query = entityManager.createNativeQuery(queryS);

Convert query to hibernate criteria query

I have the following Sybase query,
select *
from dbo.translation_style_sheet t1
where t1.create_date = (select max(t2.create_date)
from dbo.translation_style_sheet t2
where t1.file_name = t2.file_name);
I'm trying to convert it to a hibernate criteria query, but haven't been able to figure it out. I'm assuming I need to use a DetachedCriteria to handle this, but not sure how to work with it.
This is what I have thus far.
DetachedCriteria maxCreateDate = DetachedCriteria.forClass(TranslationStyleSheet.class, "translationStyleSheet2")
.setProjection( Property.forName("createDate").max() )
.add( Property.forName("translationStyleSheet2.fileName").eqProperty("translationStyleSheet.fileName") );
List<TranslationStyleSheet> translationStyleSheets = this.session.createCriteria(TranslationStyleSheet.class, "translationStyleSheet")
.add( Property.forName("createDate").eq(maxCreateDate))
.list();
I'm getting the following exception.
org.hibernate.exception.GenericJDBCException
could not execute query
SQL
select this_.translation_style_sheet_id as translat1_20_0_, this_.create_date as create2_20_0_, this_.description as descript3_20_0_, this_.file_content as file4_20_0_, this_.file_extension as file5_20_0_, this_.file_name as file6_20_0_, this_.file_size as file7_20_0_, this_.style_sheet_content as style8_20_0_, this_.style_sheet_type as style9_20_0_ from translation_style_sheet this_ where this_.create_date = (select max(translationStyleSheet2_.create_date) as y0_ from translation_style_sheet translationStyleSheet2_ where translationStyleSheet2_.file_name=this_.file_name)
SQLState
ZZZZZ
Does anybody know what I'm doing wrong?
UPDATE
The error seems to be be happening at the max(translationStyleSheet2_.create_date) as y0_
as. When I remove the as y0_ in the sql statement, I'm able to run the query the query, however I'm not sure how to repair this in hibernate criteria though.
So I had no success getting this to work as a criteria query, but I did have success getting it to work as an HQL query.
HQL solution
this.session.createQuery("from TranslationStyleSheet this "
+ "where this.createDate = (select max(translationStyleSheet2.createDate) "
+ "from TranslationStyleSheet translationStyleSheet2 "
+ "where translationStyleSheet2.fileName=this.fileName)")
.list();
I'm still interested in getting the query to work as a criteria query though.