【发布时间】:2019-08-11 00:20:14
【问题描述】:
我有一个函数可以检查 MYSQL 中的表中是否存在特定记录。
下面是这段代码:
public String get_value(long nodeid,String ts) {
try {
String sql="Select URL FROM urllink WHERE URL='f0="+nodeid+"&ts="+ts + "'";
em.createNativeQuery(sql).getSingleResult();
if (em == null) {
throw new Exception("could not found URL object.");
}
// return 1;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
在我的 JSP 页面中,我会调用这个函数并将参数传递给它。
String v=fileFacade1.get_value(fileID,date);
if(v !=null ){
// if the records exist in the table, do this
}
我正在尝试调用该函数,因此如果表中有记录,则输入 if 语句并执行某些操作,但从我调试的内容来看,v 的值始终为空,但有来自 singleresult 的记录.
我是不是做错了什么?
编辑:
这就是现在的样子:
public String get_value(long nodeid,String ts) {
try {
String sql="Select URL FROM urllink WHERE URL='f0="+nodeid+"&ts="+ts + "'";
if (em == null) {
throw new Exception("could not found URL object.");
}
em.createNativeQuery(sql).getSingleResult();
return (String)em.createNativeQuery(sql).getSingleResult();
// return 1;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
【问题讨论】:
-
em == null并不是说“没有找到对象”而是“你的容器没有正确设置”。在使用 JPA 时,如果可能的话,我也会避免使用原始 Sql -
我认为
throw new Exception("could not found URL object.");没有用。你可以删除它if (em == null) { throw new Exception("could not found URL object."); } -
@AkashShah 你说得对,那里有点毫无意义
标签: java mysql jdbc entitymanager