Java: namedquery string problem
Hello, I encountered some exact matching problems when doing 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 in most cases, but I've noticed that if the user passes a file name with a space at the end, 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 previous query Bypass my "valid entries" validation In other words, I want the query to return no entries at all and deal with the error later
One solution I can think of is to place the single quotation marks of my parameters in namedquery, as shown below:
@NamedQuery(name = MyClass.GET_ENTRY_BY_NAME,query = "select e from entry e where e.name =':"+ Entry.NAME "'")
However, if the string contains single quotes, it will discard my code
Any ideas?
Solution
I think this is because your database fields are declared char (...), so the stored values are filled with spaces, which are not taken into account by the = operation
Therefore, you can declare a database field as varchar (...) or use the built-in pruning function:
query = "select e from Entry e where trim(trailing from e.name) =:"+ Entry.NAME