i have the following situation:
In the dao class:
...
Query q = em.createNamedQuery("myQuery");
q.setParameter("attr", "value");
List<MyObj> listMyObj = q.getResultList();
...
In my file orm.xlm, i defined this query:
<named-query name="myQuery">
<query><![CDATA[
select m from MyEntity1
where id_est in (select mm.id from MyEntity2 where mm.id_est = :attr)
]]></query>
</named-query>
Everything works, there are no configuration problems and / or code, but this query returns 0 elements, when execute the same query in sql returns items expected . Why? There is something i ignore in JPQL?
In this case, if mm.id_est is a String when you set parameter don't use
" 'value' "
but use
" value "
...this was my problem. Fortunately, thanks to this post I realized that in my code I had written as I wrote here on StackOverflow
Related
I need to retrieve all the T1 objects from a table based on a condition where the expire date is null and the query should retrieve only T16_ID of three types which are A, B and C. I have the below simple SQL query for this which returns the correct result.
SELECT * FROM T1 d
WHERE d.T1_T2_ID_FK = '123'
AND d.T1_DATE_EXPIRED IS NULL
AND (d.T16_ID LIKE 'A' OR
d.T16_ID LIKE 'B'
OR d.T16_ID LIKE 'C');
I use JPA for object relational mapping in my application and below is my respective JPA query
TypedQuery<T1Docs> query = em.createQuery(
"**SELECT t FROM T1Docs t WHERE t.t1ID.t2Id = :idNum
AND t.t1DateExpired IS NULL
AND (t.t16DocType.t16Id LIKE :docType1 OR t.t16DocType.t16Id LIKE :docType2 OR t.t16DocType.t16Id LIKE :docType3**)",T1Docs.class);
query.setParameter("idNum", idNumber);
query.setParameter("docType1", "%" + "A" + "%");
query.setParameter("docType2", "%" + "B" + "%");
query.setParameter("docType3", "%" + "C" + "%");
above query doesnt return any result and when I debug the plogram I found that the query is generated as below.
SELECT t0.T1_ID, t0.T1_DATE_CAPTURED, t0.T1_DATE_EXPIRED, t0.T1_T16_ID_FK
FROM T1_OWNER_DOCUMENT t0, T16_DOC_TYPE t1 WHERE ((((t0.T1_T2_ID_FK = ?)
AND (t0.T1_DATE_EXPIRED IS NULL))
AND ((t1.T16_ID LIKE ? OR t1.T16_ID LIKE ?)
OR t1.T16_ID LIKE ?)) AND (t1.T16_ID = t0.T1_T16_ID_FK))
because of the incorrect usage of parenthesis, the generated query becomes incorrect and It doesn't return any result.
If anyone knows how to fix this issue in the JPA query because I am new to JPA and having trouble in understanding how to use OR with multiple checks along with AND and parenthesis.
I'm using EclipseLink as JPA implementation and I need to get multiple objects using the primary key (numeric id). But I also need to maintain the given id order.
Using native mySQL this kind of behaviour can be obtained using ORDER BY FIELD
SELECT id FROM table WHERE id IN(9,5,2,6) ORDER BY FIELD(id,9,5,2,6);
I'm now trying to replicate this query using JPA implementation. As already established from this thread, the ORDER BY FIELD is not supported, so I went to a more low-level approach using a JPA native query.
I'm try to reach this goal using a parameter query, instead of using a raw statement. The first implementation was like this
Class<?> clazz = ...;
List<Long> ids = ...;
EntityManagerFactory emf = ...;
EntityManager em = emf.createEntityManager();
String statement = "SELECT * FROM table WHERE id IN (?)";
Query createNativeQuery = em.createNativeQuery(statement, clazz);
createNativeQuery.setParameter(1, ids);
List resultList = createNativeQuery.getResultList();
As you can see the ORDER clause is not there yet, for the first step I just trying to make the parameter query work using the ids list with the IN operator. In the setParameter method I tried to provide the List object, a comma separated list (as string) but none of them works. At the end they all finish with a sql syntax error.
I also tried to play with the parenthesis, with or without, but nothing works.
Here some test I made
String statement = "SELECT * FROM " + tableName + " WHERE id IN (?)";
Query createNativeQuery = emJpa.createNativeQuery(statement, this.em.getClassObject());
createNativeQuery.setParameter(1, ids);
The query does not give any error, but no results given.
String statement = "SELECT * FROM " + tableName + " WHERE id IN (?)";
Query createNativeQuery = emJpa.createNativeQuery(statement, this.em.getClassObject());
createNativeQuery.setParameter(1, Joiner.on(",").join(ids));
Only one result is given, but 7 ids was provided to the query
From this topic I also tried using ?1 instead of ?, but no changes. Is there a way to make the nativeQuery working with a list of ids?
For the moment I'm using the full raw SQL statement
String joinedId = Joiner.on(",").join(ids);
String statement = "SELECT * FROM " + tableName + " WHERE id IN (" + joinedId + ") ORDER BY FIELD(id," + joinedId + ")";
Query createNativeQuery = emJpa.createNativeQuery(statement, this.em.getClassObject());
createNativeQuery.getResultList();
But at first I started with the parameter query for optimization and performance related of parsing each time the statement.
EDIT
With the suggestion of Chris I tried a TypedQuery using the FUNCTION operator (which is available because I'm using the latest EclipseLink). Here is the resulting code
List<Long> ids = ...;
Class<?> clazz = ...;
String statement = "SELECT e FROM " + clazz.getSimpleName() + " e WHERE e.id IN (:idList) ORDER BY FUNCTION('FIELD', e.id, :idList)";
EntityManagerFactory emf = ...;
EntityManager em = emf.createEntityManager();
TypedQuery<?> query = em.createQuery(statement, clazz);
query.setParameter("idList", ids);
List resultList = query.getResultList();
And here is the error while executing this code
Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Operand should contain 1 column(s)
Error Code: 1241
Call: SELECT ... all the fields ... FROM webcontent_type WHERE (ID IN ((?,?,?,?,?,?,?))) ORDER BY FIELD(ID, (?,?,?,?,?,?,?))
bind => [14 parameters bound]
Query: ReadAllQuery(referenceClass=WebContentType sql="SELECT ... all the fields ... FROM webcontent_type WHERE (ID IN (?)) ORDER BY FIELD(ID, ?)")
EDIT 2
Tried without the parenthesis but there is still an error
SELECT e FROM FrameWorkUser e WHERE e.id IN :idList ORDER BY FUNCTION('FIELD', e.id, :idList)
I must say that with a list of one element the code works, but with another list of 10 elements there is an error
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Operand should contain 1 column(s)
Error Code: 1241
Call: SELECT .... FROM webcontent_type WHERE (ID IN (?,?,?,?,?,?,?)) ORDER BY FIELD(ID, (?,?,?,?,?,?,?))
bind => [14 parameters bound]
Query: ReadAllQuery(referenceClass=WebContentType sql="SELECT .... FROM webcontent_type WHERE (ID IN ?) ORDER BY FIELD(ID, ?)")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:382)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:473)
It seems that even w/o the parenthesis, the resulting statement has them
If you are going to use a native query, you must do it exactly like you would form the SQL for your database - this means you must break the list into its component parameters as JPA providers are not expected to change the SQL for you. Most providers handle lists in JPQL though, so "select e from Entity e where e.id in (:idList)" will work in EclipseLink.
Your missing bit is that 'FIELD' is not a JPQL construct. For this, you would have to use the JPQL 2.1 FUNCTION operator. Something like:
"Select e from Entity e where e.id in :idList order by FUNCTION('FIELD', e.id, :idList)"
I'm very, very new to Hibernate and JPA. I want to be able to apply ORDER BY and LIMIT clauses to a Hibernate(?) query, but am coming up empty. NOTE: I inherited this code.
Here is the current code:
public SomeCoolResponse getSomeCoolResponse(String myId) {
String queryString = "select aThing from AWholeBunchOfThings aThing " +
"join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " +
"where saThing.subthing.id = :id";
Query q = getEntityManager().createQuery(queryString);
q.setParameter("id", myId);
List<MyThings> list = q.getResultList();
if(list.size() > 0) {
return list.get(0);
}
return null;
}
Instead of getting an entire list and then just returning the first result (which is the only one we need), I'd like to be able to apply a LIMIT 0,1 clause so that the query will be faster. Also, the query needs to be sorted descending on aThing.created which is a UNIX timestamp integer.
I've tried altering queryString like this:
String queryString = "select aThing from AWholeBunchOfThings aThing " +
"join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " +
"where saThing.subthing.id = :id ORDER BY aThing.created LIMIT 0,1";
But Hibernate still returns the entire set.
I've looked at using the JPA CriteriaBuilder API, but it hurt my brain.
I'm a total n00b when it comes to this, and any help is greatly appreciated!
I think you need
q.setMaxResults(1);
See also the accepted answer here.
How do you do a limit query in HQL?
As to the "order by" clause you may include it in the queryString.
The JPQL equivalent to LIMIT start,max is:
setFirstResult and setMaxResults:
q.setFirstResult(start);
q.setMaxResults(limit);
I am getting the following error on the execution of the below hibernate transaction : expecting DOT, found '=' near line 1, column 32 [update t_credential set status = :status , assigned_engine = :engine where id = :id] .
Also, t_credential is a table and not an object. Does hibernate allow to use this way or does it compulsorily have to be an object?
for(Credential credential: accountList){
Query query = ssn.createQuery("update t_credential set status =:status , assigned_engine = :engine where id = :id");
query.setParameter("status", status);
query.setParameter("engine", assignedTo);
query.setParameter("id", String.valueOf(credential.getId()));
int result = query.executeUpate();
}
Look at the HQL example here: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html#batch-direct. It seems that you need to refer to an object: "update t_credential c", and then update it's fields, like this: "set c.status = :status" and so on.
If you want to use Hibernate with SQL Query (and not HQL query), you may have to use a different function.
ssn.createSQLQuery(" ... ");
I never used this function, so I hope it's a good answer for you.
Max
I wonder if there is a good solution to build a JPQL query (my query is too "expressive" and i cannot use Criteria) based on a filter.
Something like:
query = "Select from Ent"
if(parameter!=null){
query += "WHERE field=:parameter"
}
if(parameter2!=null) {
query += "WHERE field2=:parameter2"
}
But i would write WHERE twice!! and the casuistic explodes as the number of parameter increases. Because none or all could be null eventually.
Any hint to build these queries based on filters on a proper way?
select * from Ent
where (field1 = :parameter1 or :parameter1 is null)
and (field2 = :parameter2 or :parameter2 is null)
Why can't you use a criteria, like this.
Other options (less good imho):
Create two named queries one for each condition, then call the respective query.
Or build up a string and use a native query.
Oh, do you just mean the string formation(?) :
query = "Select from Ent where 1=1 "
if(parameter!=null){
query += " and field=:parameter"
}
if(parameter2!=null) {
query += " and field2=:parameter2"
}
(I think that string formation is ugly, but it seemed to be what was asked for)