您好我在我的 Controller 上有这个方法。我想要的是当我传递一个地名时它必须检查它是否存在..如果它存在则返回 true 否则返回 false
@Override
@Transactional
public boolean alreadyExists(String place) {
boolean flag=false;
sessionFactory.getCurrentSession().createQuery("from Place where place_Name='$"+place+"'");
return flag;
}
最佳答案
没有任何断言您现有查询的正确性或有效性...
有一种简单的方法:如果您期望只有一个 Place
ever 存在,那么您可以使用 uniqueResult
, 如果存在则返回实体的实例,如果不存在则返回 null
:
@Tranasctional
public boolean alreadyExists(String place) {
return sessionFactory.getCurrentSession()
.createQuery("from Place where place_Name=:place")
.setParameter("place", place)
.uniqueResult() != null;
}
您还可以将结果作为列表获取,并检查列表是否不为空(这意味着有结果)。
@Tranasctional
public boolean alreadyExists(String place) {
List result = sessionFactory.getCurrentSession()
.createQuery("from Place where place_Name=:place")
.setParameter("place", place)
.list();
return !result.isEmpty();
}
关于java - 如何使用 Hibernate Spring 检查表中已存在的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23026973/