Using LIKE operator in Access works but not in Java - java

I'm making a java application for a toy store and using the MS-Access database.
I'm using the operator "LIKE" to search for products in database using the user's keyword.
E.g. in Access:
SELECT * FROM tblToy WHERE toyName LIKE '*puppy*' OR toyBrand LIKE '*puppy*'
this gives me the desired result in access.
But in java when i run this same query it returns null:
String query = "puppy";
sql = "SELECT * FROM tblToy WHERE toyName LIKE '*" + query+"*' "+
"OR toyBrand LIKE '*" + query + "*'";
rs = db.executeQuery(sql);
while(rs.next()){
String name = rs.getString("toyName");
return name;
}
return null;
Can anyone help me on this? I know it must be something simple which I'm missing out now but I just don't know what to do. Would appreciate your guys help.

I think with Java, you need to escape single quotes, so try using \' for all your single quotes, then try % instead of * as someone else mentioned, since % is the wildcard for SQL.

There are two possibilities for wildcards according to where you are running the query, * or %. In this case, you need %

Related

how to use setParameter for date field in where condition in sql query " date like :today " using hibernate

I am having trouble while trying to implement where condition with " punchDate like :date1 " in sql query using hibernate. Can any one please tell me what is the correct syntax to implement it.
String sql=select * from PunchHistory whered punchDate like :date1;
String date="2017-10-23";
List<PunchHistory> results =session.createQuery(StackperksConstants.sql)
.setDate("date1", java.sql.Date.valueOf(date))
.list();
Could anyone please help me.
Thanks in advance
Like is used with Strings, instead you have to use = with dates :
String sql="select * from PunchHistory where punchDate = :date1"
//-----------------------------------------------------^
List<PunchHistory> results =
session.createQuery(StackperksConstants.sql)
.setParameter("date1", java.sql.Date.valueOf(date), TemporalType.TIMESTAM)
//Instead you can use -----^
.list();
The better way is using the setParameter() method, for example:
session.createQuery(sql,Class.class).setPrameter(0,date,TemporalType.TIMESTAMP).list();

Fetching data with Special Characters from HQL

I have a search functionality that is implemented on my current project, I am using HQL for the repo method - Everything is okay except searching for special characters for some reason HQL is not escaping it.
#Query("SELECT f FROM Item f WHERE f.id=:id AND f.itemNm LIKE %:itemNm %")
Item findByItemNm(#Param("itemNm ") String itemNm, #Param("id") Long id);
The String search I am sending is
abc_xyz(YYYYMM[t-2]-YYYYMM[t-1])_[xyz]HU.xlsx
Debugging Steps
Before sending to the Repo - I did replace all the special characters with the following -newsearchString is the one thatt is being passed to the repo
String newsearchString = searchString.replaceAll("(?=[]\\[+&|!(){}^\"~*?:\\\\_]) ", "/");
I have also tried it without replacing the special characters- It is not being returned
How do you escape characters in HQL?
Here is the solution for your problem...It should work for your need.
1) Find and replace all your escape characte, and replaced by "\\"
Example: [hi]_mysearch should be replaced like \\[hi\\]_mysearch
2) Change your repo query like below
#Query("SELECT f FROM Item f WHERE f.id=:id AND f.itemNm LIKE %:itemNm % escape '\\'")
Item findByItemNm(#Param("itemNm ") String itemNm, #Param("id") Long id);
HQL does not have regular expressions out of the box. You'd have to modify the Dialect for your specific database to add that functionality. (Oracle example)
If you're just trying use like with the % wildcard, then you can do the following:
String itemNm = "abc_xyz(YYYYMM[t-2]-YYYYMM[t-1])_[xyz]HU.xlsx";
Query q = session.createQuery("from Item where itemNm like :itemNm ";
q.setString("itemNm","%"+itemNm+"%");

Can we replace UPPER function by making upper in java?

I want remove upper function used in hql and make in upper at java side. following is the query:-
String hql = "SELECT addType FROM addrDO WHERE **UPPER**(id.address) = **UPPER**('"+ address +"')";
I want use toUpperCase() java funtion instead of using UPPER in query, like "id.address".toUpperCase() and address.toUpperCase() at java side and now query should be like
String hql = "SELECT addType FROM addrDO WHERE id.address = address;
Will above work any side effect.
The first query uses the UPPER function to implement a case insensitive comparison in the WHERE clause, the second uses case sensitive comparison.
Because the comparison has to be done in the database, you cannot replace it with Java's toUpperCase in the application layer.
You are trying to generate a dynamic query, which would finally be executed by a database server and not in JVM, thus you need to abide by the grammar of database server.
If you want to use java's toUpperCase method, better break your query and have something like
String idAddress = "id.address";
String address = "'\"+ address +\"'";
String hql = "SELECT addType FROM addrDO WHERE "+ idAddress.toUpperCase() +" = " + address.toUpperCase() + ";";
which is not suggestible, as you are unnecessarily using up jvm's memory

Problem with JDOQL to obtain results with a "contains" request

I am using Google App Engine for a project and I need to do some queries on the database. I use the JDOQL to ask the database. In my case I want to obtain the university that contains the substring "array". I think my query has a mistake because it returns the name of universities in the alphabetical order and not the ones containing the substring.
Query query = pm.newQuery("SELECT FROM " + University.class.getName() + " WHERE name.contains("+array+") ORDER BY name RANGE 0, 5");
Could someone tell me what's wrong in my query?
Thank you for your help!
EDIT
I have a list of universities store and I have a suggestbox where we can request a university by his name. And I want to autocomplete the requested name.
App engine does not support full-text searches, you should star issue 217. However, A partial workaround is possible. And in your case I think it is a good fit.
First thing, adjust your model such that there is a lower (or upper case) version of the name as well -- I will assume it is called lname. Unless you want your queries to be case-sensitive.
Then you query like this:
Query query = pm.newQuery(University.class);
query.setFilter("lname >= startNameParam");
query.setFilter("lname < stopNameParam");
query.setOrdering("lname asc");
query.declareParameters("String startNameParam");
query.declareParameters("String stopNameParam");
query.setRange(0, 5);
List<University> results = (List<University>) query.execute(search_value, search_value + "z");
The correct way to do this is like this -
Query query = pm.newQuery(University.class,":p.contains(name)");
query.setOrdering("name asc");
query.setRange(0, 5);
List univs = q.execute(Arrays.asList(array));
(note- In this case the :p is an implicit param name you can replace with any name)

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