Why does this JPQL fail with message "You have attempted to set a parameter at position x which does not exist in this query string"? - jpa

I have the following named query:
#NamedQueries({
#NamedQuery(name ="Movies.findByTitle", query = "SELECT m FROM Movies m WHERE m.title = :title")
})
When I try to execute it as follows:
public List<T> findByTitle(String title) {
return getEntityManager().
createNamedQuery("Movies.findByTitle").
setParameter("findByTitle", title).
getResultList();
}
Then I get the following exception:
You have attempted to set a parameter value using a name of findByTitle that does not exist in the query string SELECT m FROM Movies m WHERE m.title = :title.
How is this caused and how can I solve it?

You need to set a correct parameter name.
You can see in your query the parameter is named "title" not "findByTitle".
setParameter("findByTitle", title) change this to setParameter("title", title)

Related

sqflite IN operator with AND operator

I have following query which select from employee table where name is "max" and ID not in 123 and 444.
Not in IDs can grow in future. But I am receiving error as
Error
( 8023): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: DatabaseException(near "?": syntax error (code 1 SQLITE_ERROR): , while compiling:
Query
List<String> a = [];
a.add("123");
a.add("444");
var table = await mydb.rawQuery(
"SELECT value from employee WHERE employeename = ? AND id NOT IN ? ORDER BY timestamp DESC",
["max", a]);
If the LIST is unpredictable, one way is that you can use JOIN to create your select statement with required value of NOT IN. Below is one sample.
void main() {
List<String> a = [];
a.add("123");
a.add("444");
var select =
'SELECT value from employee WHERE employeename = ? AND id NOT IN (\'' +
(a.join('\',\'')).toString() +
'\') ORDER BY timestamp DESC';
var table = await mydb.rawQuery(select, ["max"]);
}
If you print the variable select you will get
SELECT value from employee WHERE employeename = ? AND id NOT IN ('123','444')
ORDER BY timestamp DESC.
Then you can pass the above statement to rawquery and get your result.
P.S:Use your single quote and double quote accordingly.
I'd go for #arun-palanisamy 's solution, see his comment. Props go to him. I just tried the following -- with Groovy/Postgres, but the error seems to be the same, so you might want to give it a try:
String[] a = ['123', '444']
// your code, throws 'ERROR: syntax error at or near "$2"':
// def table = sql.execute("SELECT value from employee WHERE employeename = ? AND id NOT IN ? ORDER BY timestamp DESC", ["max", a])
// code of arun-palanisamy, compiles:
def table = sql.execute("SELECT value from employee WHERE employeename = ? AND id NOT IN (${a.join(', ')}) ORDER BY timestamp DESC", ["max", a])
Side notes:
You might want to try a different type for a, such as Array in my code, or even a HashMap.
There are examples (like here) where the number of ? are generated dynamically.
Update: Go for this answer, we posted simultaneously

How can i ignore: PSQLException: The column name clothStyle was not found in this ResultSet

I created a a query to only get 4 items from a row in a table which does not include the column cloth style, so i understand why i get the error, but how can i tell Spring Jpa or JPA it is on purpose. and i just want the id, name and color table ?
this is my code:
#RequestMapping(value = "/query/material",method = RequestMethod.GET)
public String QueryMaterialTable(HttpServletRequest request){
DataTableRequest<Material> dataTableInRQ = new DataTableRequest<Material>(request);
PaginationCriteria pagination = dataTableInRQ.getPaginationRequest();
String baseQuery = "SELECT id as id, time as time, name as name, color as color, price as price, (SELECT COUNT(1) FROM MATERIAL) AS totalrecords FROM MATERIAL";
String paginatedQuery = AppUtil.buildPaginatedQuery(baseQuery, pagination);
System.out.println(paginatedQuery);
Query query = entityManager.createNativeQuery(paginatedQuery, Material.class);
#SuppressWarnings("unchecked")
List<Material> materialList = query.getResultList();
DataTableResults<Material> dataTableResult = new DataTableResults<Material>();
dataTableResult.setDraw(dataTableInRQ.getDraw());
dataTableResult.setListOfDataObjects(materialList);
if (!AppUtil.isObjectEmpty(materialList)) {
dataTableResult.setRecordsTotal(String.valueOf(materialList.size())
);
if (dataTableInRQ.getPaginationRequest().isFilterByEmpty()) {
dataTableResult.setRecordsFiltered(String.valueOf(materialList.size()));
} else {
dataTableResult.setRecordsFiltered(String.valueOf(materialList.size()));
}
}
return new Gson().toJson(dataTableResult);
}
If I got the question right, your problem is with the following two lines:
Query query = entityManager.createNativeQuery(paginatedQuery, Material.class);
List<Material> materialList = query.getResultList();
You have various options to fix this:
provide a complete column list, i.e. provide the missing column in the SQL statement and just make them NULL;
Don't use Material but a new class that has the matching attributes.
Don't use a native query but JPQL and a constructor expression.
Use a ResultTransformer.
Use Spring Data and a Projection.
Use a Spring JdbcTemplate.

JPQL: Parameter with that position [1] did not exist

I am working with JPA and JPQL. Using a JPQL I would like to fetch join a collection that is an attribute of a "main" entity rent. Here is my source code:
public Rent getRentWithAllDetails(Rent rent) {
Query queryString = em.createQuery(" select r from Rent r JOIN FETCH r.rentables where r.id = :rid").setParameter(1, rent.getId());
List <Rent> resultList = queryString.getResultList();
return resultList.get(0);
}
and this is the exception I recieve:
Caused by: java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:518) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:674) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:198) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:49) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
Could someone help me, please?
You are using a named parameter, so you should bind a parameter by that name while creating your query:
String sql = "select r from Rent r JOIN FETCH r.rentables where r.id = :rid";
Query queryString = em.createQuery(sql)
.setParameter("rid", rent.getId());
List<Rent> resultList = queryString.getResultList();
Please change your code to:
public Rent getRentWithAllDetails(Rent rent) {
Query queryString = em.createQuery(" select r from Rent r JOIN FETCH r.rentables where r.id = :rid").setParameter("rid", rent.getId());
List <Rent> resultList = queryString.getResultList();
return resultList.get(0);
}
if rid is repeated multiple times, you can use 0,1..etc accordingly, otherwise use the parameter name itself.

DistinctResultList in OpenJPA

I am attempting to get a distinct list of id's back that would be longs... But I am getting back this DistinctResultList... How can one handle this so that they get back results they are expecting... Here is what I am doing...
#NamedQuery(name="getProvidersByResourceIds", query = "SELECT DISTINCT p.resourceId FROM Provider p WHERE p.resourceId `in :resourceIds")`
Out of that I try and get the resourceIds' by doing this...
List<Long> provIDs = (List<Long>) emf.createNamedQuery("getProvidersByResourceIds").setParameter("resourceIds", values).getResultList();
But like I said, I keep getting back a DistinctResultList... Looking through the debugger, I can see the values I am getting back. How can I translate this into something usefull?
javax.ejb.EJBException: See nested exception; nested exception is: java.lang.IllegalArgumentException: Parameter "Parameter<long>('resourceIds')" declared in "SELECT p FROM Provider p WHERE p.resourceId = :resourceIds" is set to value of "org.apache.openjpa.kernel.DistinctResultList#35fb35fb" of type "org.apache.openjpa.kernel.DistinctResultList", but this parameter is bound to a field of type "long".
java.lang.IllegalArgumentException: Parameter "Parameter<long>('resourceIds')" declared in "SELECT p FROM Provider p WHERE p.resourceId = :resourceIds" is set to value of "org.apache.openjpa.kernel.DistinctResultList#35fb35fb" of type "org.apache.openjpa.kernel.DistinctResultList", but this parameter is bound to a field of type "long"
Change your query to :
#NamedQuery(name="getProvidersByResourceIds",
query = "SELECT DISTINCT p.resourceId FROM Provider p WHERE p.resourceId in (:resourceIds)");

JPA NamedQuery get distinct column

I want to get an list of distinct City's from my User table. I thought the code below would work but gives an error:
User.java
#Entity
#Table(name="user_info")
...
#NamedQuery(name = "User.all.cities", query = "SELECT distinct u.city FROM User u"),
...
#embedded
private City city;
UserBusinessLogic.java:
...
TypedQuery<City> typedQuery = entityManager.createNamedQuery("User.all.cities",User.class);
List<City> names = typedQuery.getResultList();
...
It gives: type mismatch can not convert List to List. I tried two get first user then on getResult a City but same error one line below.
I see some examples but not really tell how to get it with correct code just the SQL syntax.
Thanks for your help
Jess
The first thing which doesn't look good is that you ask for City objects but declare to get User's.
You have:
#NamedQuery(name = "User.all.cities",
query = "SELECT distinct u.city FROM User u"),
TypedQuery<City> typedQuery =
entityManager.createNamedQuery("User.all.cities", User.class);
Where it should be:
TypedQuery<City> typedQuery =
entityManager.createNamedQuery("User.all.cities", City.class);
The code that works is:
results = getJpaTemplate().execute(new JpaCallback<List<City>>() {
#Override
public List<City> doInJpa(EntityManager em) throws PersistenceException {
TypedQuery<City> query = em.createNamedQuery("User.all.cities", City.class);
return query.getResultList() ;
}
}) ;