Reputation: 141
In my spring application, I have added a search function where the user can search the database for a name, it works except when I'm searching for names or similar names, but for when the I enter nothing and search, it should return nothing but returns the full list of names.
I set the list to return null if it is null, what is the flaw in my logic?
from testing and using the findbyname SQL I think it is a flaw in my SQL state
the controller method used is
@RequestMapping("search")
public ModelAndView SearchBeers(@RequestParam("searchTerm") String searchTerm) {
return new ModelAndView("/Searchbeers", "beerList", service.Search(searchTerm));
}
service method called is
public List<Beers> Search(String searchTerm) {
EntityManager em = DBUtil.getEMF().createEntityManager();
List<Beers> list = null;
try {
list = em.createNamedQuery("Beers.findByLikeName", Beers.class)
.setParameter("name", searchTerm)
.getResultList();
if (list == null || list.isEmpty()) {
list = null;
}
} finally {
em.close();
}
return list;
}
and the SQL statement used is
@NamedQuery(name = "Beers.findByLikeName", query = "SELECT b FROM Beers b WHERE b.name LIKE CONCAT('%',:name,'%')")
the JSP for when displaying the list is
<c:forEach items="${beerList}" var="beer">
<tr>
<td>${beer.id}</td>
<td>${beer.name}</td>
<td>${beer.abv}</td>
<td>
<form action="/Assignment3/beer/viewBeer">
<input type="hidden" name="id" value="${beer.id}"/>
<input type="submit" value="<spring:message code="label.viewDetails"/>"/>
</form>
</td>
</tr>
</c:forEach>
Upvotes: 1
Views: 174
Reputation: 506
You have many ways to solve that, but the problem is, when the String is empty your query is:
SELECT b from Beers b Where b.name LIKE '%%'
So, you need do antoher flag, when have an empty String, because ... LIKE '%%'
find every name.
PD: Not a good practice return a null, is better a empty list.
Upvotes: 1