我正在尝试使用下面的代码在数据存储区中搜索一些类型为“Book”的实体。但是它返回空List.I得到一个空的结果列表,其中size = -1。我在哪里出错?
@ApiMethod(name = "searchBook")
public List<Book> searchBook(@Named("bookName") String bookName,@Named("languageId")String languageId, @Named("subjectId")String subjectId) {
EntityManager mgr = getEntityManager();
List<Book> bookList=new ArrayList<Book>();
String queryString="";
queryString="SELECT x FROM Book x WHERE ";
//If i dont want to set any parameter for some field, I send BLANK as the parameter..
if(bookName!=null && !bookName.matches("BLANK")){
queryString=queryString+"x.bookName =:bookName"+" AND ";
}
if(languageId!=null && !languageId.matches("BLANK")){
queryString=queryString+"x.languageId =:languageId"+" AND ";
}
if(subjectId!=null && !subjectId.matches("BLANK")){
queryString=queryString+"x.categoryId =:subjectId"+" AND ";
}
//Removing last word "AND" and whitespaces from the end of queryString
queryString=queryString.substring(0,queryString.length()-5);
Query q = mgr.createQuery(queryString);
//setting query parameters..
if(bookName!=null && !bookName.matches("BLANK")){
q.setParameter("bookName", bookName);
}
if(languageId!=null && !languageId.matches("BLANK")){
q.setParameter("languageId", languageId);
}
if(subjectId!=null && !subjectId.matches("BLANK")){
q.setParameter("subjectId", subjectId);
}
//executing the query...
try {
mgr.getTransaction().begin();
bookList = (List<Book>) q.getResultList();
mgr.getTransaction().commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
mgr.close();
}
return bookList;
}
在我的情况下,我通过仅为subjectId设置一个参数进行了测试。设置参数有问题吗?这是在查询中设置动态参数数量的正确方法吗?