以下方法使用 Java 实体管理器的 createNativeQuery() 方法:
public List<Dog> findDogById(String id) {
List<Dog> resultList = new ArrayList<>();
try {
resultList = persistence.entityManager().createNativeQuery(" SELECT * FROM DOG WHERE ID = '" + id+ "' ", DogEntity.class).getResultList();
} catch (Exception e) {
}
return resultList;
}
我遇到的问题是,当我期望该方法返回结果时,它不返回结果。 IE。当我直接通过
SQL Developer
运行查询时,我得到结果,但该方法不会返回相同的结果。
我的
Syntax
正确吗?我对此不确定:
" SELECT * FROM DOG WHERE ID = '" + id+ "' "
即我需要
'
和 "
吗?
您的语法是正确的,但您的代码中存在其他问题。
你默默地忽略了异常。您可能会遇到异常,忽略它然后返回空列表:
try {
resultList = persistence.entityManager().createNativeQuery(" SELECT * FROM DOG WHERE ID = '" + id+ "' ", DogEntity.class).getResultList();
} catch (Exception e) {
// If an exception is thrown in this try block, you are ignoring it.
}
如果您使用没有参数绑定的查询,则可能会遇到 SQL 注入问题。举个例子,如果有人在您的函数中发送
0' OR 1=1--
作为 id,用户将获得狗的完整列表。
使用参数并避免此类问题,查询也更具可读性且不易出错:
.createNativeQuery(" SELECT * FROM DOG WHERE ID = ?1", DogEntity.class)
.setParameter(1, id)
.getResultList();
为了避免出现问题,您应该使用参数:
Query query = em.createNativeQuery("SELECT * FROM DOG WHERE ID = ?");
query.setParameter(1, id);