IllegalArgumentException - Parameter with that name [name] did not exist - java

I have a this query on my code:
return Long.parseLong(getEntityManager().createQuery(
"SELECT COUNT(a) FROM ApartmentExtraType a WHERE a.accommodation.id = :idacc AND (LOWER(a.name) LIKE :name)",
Long.class)
.setParameter("idacc", accommodation.getId())
.setParameter("name", "%" + filterQuery.getFieldFilter("name").toString().toLowerCase() + "%")
getSingleResult().toString());
If the query don't find any element i have no problem, but if it found at least one element I have this error:
Last cause: Parameter with that name [name] did not exist WicketMessage: Error attaching this container for rendering:
[WebMarkupContainer [Component id = tbody]]
The name of the relative column is "name" and I'm sure. Other query seems to be identical to this one and they work fine. I don't know which is the problem

Looks like the issue is not with the column name it is with the parameter you are passing in called "name." The "idacc" one looks like it was grabbed correctly.
So this part is not working
filterQuery.getFieldFilter("name").toString().toLowerCase()
Try passing in a String and see if that works something like
.setParameter("name", "ExampleName");
If that runs fine then there is something wrong with the getFieldFilter function

I resolved. The problem was that the query is composed in different method because it vary depending on user's input and in one of this method a variable was badly instantiated. So the JVM didn't find the part of the query with the [name] parameter.

Related

How to pass null to SQL parameter in java?

I have a scenario where in i have to pass null to a SQL parameter through java but i am getting SQLGrammarException. If i am passing some value it works fine. Please guide if i am wrong somewhere.
Below is my code:
StringBuffer query;
query = new StringBuffer(
"SELECT * "+
"FROM table(package.func(travel_type => travel_search_type("+
"travel_place_no => :travelPlaceNo"+
")))" );
Query query1 = em.createNativeQuery(query.toString());
query1.setParameter("travelPlaceNo",null);
searchresults = query1.getResultList();
Exception:
org.hibernate.exception.SQLGrammarException
This is what i do through SQL Developer and it works fine:
SELECT *
FROM table(package.func(travel_type => travel_search_type(
travel_place_no => NULL))) ;
Please guide.
While calling the 2 argument signatures of the method, null is not an allowed value. You can use, instead, the 3 argument signature setParameter(String name,
Object val,
Type type) specifying the data type and it should work.
EDIT:
Ok, I see there is also another problem: even if the replacemente worked, what you are trying to execute is a >= NULL. In this case, I'm afraid that you are going to have to handle mannually the StringBuffer creation. Maybe just force an always false condition without parameters if its null, like `1!=2', and otherwise just handle it as you are doing on your sql example (write mannually 'NULL' instead of the parameter placeholder).

Google app engine query with a list of string

I have a list of property values named 'token'. I am trying to filter an entity of kind
This is what i have tried.
List<String> tokens = getTokensFrom(invitations);
PersistenceManager pm = this.dataStoreService.getObjectDBConnection();
Query query = pm.newQuery(Invitations.class);
query.setFilter("tokens.contains(token)");
query.declareVariables(List.class.getName() + " tokens");
List<Invitations> invites = (List<Invitations>) query.execute(tokens);
But I'm getting the below error message.
Problem with query <SELECT FROM com.mypackage.shared.domainobjects.Invitations WHERE tokens.contains(token) VARIABLES java.util.List tokens>: Unsupported method <contains> while parsing expression: InvokeExpression{[VariableExpression{tokens}].contains(PrimaryExpression{token})}
com.google.appengine.datanucleus.query.DatastoreQuery$UnsupportedDatastoreFeatureException: Problem with query <SELECT FROM com.testbudha.shared.domainobjects.PublishedExam WHERE tokens.contains(token) VARIABLES java.util.Collection tokens>: Unsupported method <contains> while parsing expression: InvokeExpression{[VariableExpression{tokens}].contains(PrimaryExpression{token})}
at com.google.appengine.datanucleus.query.DatastoreQuery.newUnsupportedQueryMethodException(DatastoreQuery.java:993)
at com.google.appengine.datanucleus.query.DatastoreQuery.handleContainsOperation(DatastoreQuery.java:971)
at com.google.appengine.datanucleus.query.DatastoreQuery.addExpression(DatastoreQuery.java:830)
at com.google.appengine.datanucleus.query.DatastoreQuery.addFilters(DatastoreQuery.java:739)
at com.google.appengine.datanucleus.query.DatastoreQuery.compile(DatastoreQuery.java:248)
at com.google.appengine.datanucleus.query.JDOQLQuery.performExecute(JDOQLQuery.java:158)
at org.datanucleus.store.query.Query.executeQuery(Query.java:1789)
at org.datanucleus.store.query.Query.executeWithArray(Query.java:1666)
at org.datanucleus.api.jdo.JDOQuery.execute(JDOQuery.java:243)
I had a similar problem previously but it works because the filter criteria was the other way round i.e. this.token.contains(tokens) where 'token' was part of the entity and was of type List of String. But I'm not sure why this is not working. Can someone please help me?
You declare some variable called "tokens" yet pass in a parameter (presumably what you intended to be the tokens variable). A variable is not a parameter, they are different. Either use an explicit parameter, or an implicit parameter (with : prefix) as any decent JDO docs would tell you

#Resolved - Positional parameter does not exist in query // stored function call

I have this method to call a stored function from ORACLE, in java (spring) - using entity manager + createNativeQuery ..
(...)
String set_professional = "{? = call
pk_backoffice.set_professional(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?}";
//32 parameters IN
query = entity.createNativeQuery(set_professional);
(...)
And everytime I try to test it, it shows:
Positional parameter does not exist: 31 in query: {? = call (...)
But do I have something at position 31..it exists..
query.setParameter(31, prof.getFax()); // fax
Also, I started the parameters at 1 cause in previous exceptions it said it was 1-based
I've tried with a string and a null value instead of the get, still the same outcome..
About the query, I also counted the ? many times, so I'm sure it has 32 (for parameters) + 1(return - first ?)...
Can anyone help?
Found a solution, I replaced all ? for variables, even the first one, and the error disappeared.

Passing String value to SQL bigint column

Given following Statment:
String query = "Select * from T_spareParts where SparePartPK IN (? )"
In my BackBean (JSF 2) I first iterate through all cars in table and build a String of all the cars currently selected (by picking each cars ID as primary key) so the final String before being passed to SQL could look like:
String finalString = " '1','2','3','4'";
And then :
this.prepareStatement= this.connection.prepareStatement(query);
this.prepareStatement.setString(1,finalString);
this.prepareStatement.executeQuery();
Exception thrown is:
Error converting data type nvarchar to bigint.
Now my understanding is that exception is due to SparePartPK is type bigint and we're passing a String .
But in SQL Server (2008) i can do :
Select * from T_spareParts where SparePartPK IN ('1','2','3','4')"
which returns results as expected. Why am i getting the exception and how can i correct the issue? (also feel free to comment if this isn't the best approach)
Update:
I've also tried to produce the finalString without single quotes which causes the same exception to be thrown :
String finalString = " 1,2,3,4";
You should put the numbers into an array (not a string), and use preparedStatement.setArray()
Thanks for the suggestions. Though as an alternative I created a StoredProcedure where it takes one parameter and inside the StoredProcedure i run the above Query in question formulating the IN section using the passed parameter .
So all above code still applies, The parameter passed to the storeDProcedure is one String separated by , without the single quotes.
Might not be the optimum answer but works quit well :) .

JAVA: NamedQuery String problem

Hello guys I am having some problems with exact matches while doing a NamedQuery.
I am currently using something like this:
#NamedQuery(name = MyClass.GET_ENTRY_BY_NAME, query = "select e from Entry e where e.name =:"+ Entry.NAME )
...
Query query = em.createNamedQuery(MyClass.GET_ENTRY_BY_NAME);
query.setParameter(Entry.NAME, myEntry.getName());
It works for most cases, however I noticed that in case the user pass the file name with an space at the end, the namedQuery ignores that character. For example:
Query query = em.createNamedQuery(MyClass.GET_ENTRY_BY_NAME);
query.setParameter(Entry.NAME, myEntry.getName()+ " ");
Will return the same result as the query before. Bypassing my 'valid entry' validation. In other words I'd like the query to return no entry at all and treat the error later on.
One workaround I could think of, is to put single quotes surrounding my parameter in the namedQuery, like this:
#NamedQuery(name = MyClass.GET_ENTRY_BY_NAME, query = "select e from entry e where e.name =':"+ Entry.NAME "'")
However it will trash my code in case the String contains single quotes in it...
Any ideas guys?
I guess this happens because your database field is declared as CHAR(...), and therefore stored values are padded with whitespaces which are not taken into account by = operation.
So, you may either declare your database field as VARCHAR(...) or use a built-in trim function:
query = "select e from Entry e where trim(trailing from e.name) =:"+ Entry.NAME
I did some research in JPA and found out that it does some automatic trimming for CHARs, I am not sure if this behaves the same with Strings, but since it is happening to me... I believe so. The only way to bypass it is by setting some attribute within the session DatabaseLogin object (see http://www.eclipse.org/eclipselink/api/1.1/org/eclipse/persistence/sessions/DatabaseLogin.html#setShouldTrimStrings) .
Well I didn't want to be messing up with the session properties so I decided to make some sort of check and throwing the same exception as the NoResultException catch does in my code.
I basically took the result from the database and compared the field with the String I used:
query.setParameter(Entry.NAME, myEntry.getName());
...
if(!StringUtils.equals(result.getName(), myEntry.getName()){
do a cool throw just like NoResultException Catch
}
I also had to include the Trim function axtavt! This is just to make sure that if the database has a column with trailing spaces and it matches the parameter given by the user, it will be included as a valid answer. For example:
Database entry: Name = "Flavio " - Trimmed with Function = "Flavio".
Parameter passed: Name = "Flavio " - Trimmed by JPA automatic function = "Flavio".
If it isnt trimmed at all it will just Compare "Flavio " with "Flavio", returning NoResult when it was supposed to return that Entry.
Nasty workaround, but as long as there is no other way to stop the auto-trimming we will have to just make use of this sort of things.
Thanks for all the other answers!!

Categories

Resources