我正试图打印sql查询结果,但显示找不到列,
public class SearchDriver {
@Autowired
EntityManager entityManager;
public void search(String key, String value){
List<Driver> resultDerivers = entityManager.createNativeQuery("select * from driver where "+key+"="+value).getResultList();
System.out.println(resultDerivers);
//end of method
}
错误
Hibernate: select * from driver where age=45
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement
2021-02-08 18:59:19.967 WARN 11936 --- [nio-8080-exec-8] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42122, SQLState: 42S22
2021-02-08 18:59:19.967 ERROR 11936 --- [nio-8080-exec-8] o.h.engine.jdbc.spi.SqlExceptionHelper : Column "45" not found; SQL statement:
select * from driver where username=driver05 [42122-197]
2021-02-08 18:59:19.983 ERROR 11936 --- [nio-8080-exec-8] com.util.LoggingInterceptor : method: GET uri: /v1/drivers/searchBy/username/driver05 status: 200 remoteAddress: 0:0:0:0:0:0:0:1
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1423) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.query.Query.getResultList(Query.java:146) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at com.freenow.service.driver.DefaultDriverService.searchByCriteria(DefaultDriverService.java:126) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:684) ~[spring-aop-5.0.10.RELEASE.jar:5.0.10.RELEASE]
1条答案
按热度按时间nuypyhwy1#
sql查询中的字符串值必须用引号括起来,因此在您的情况下,您的代码应该检查该值是否是字符串,在本例中,在该值之前和之后加上“add”,并将该值添加到查询中。或者,要使其更清晰,请使用不同的方法,一个用于数值,一个用于字符串,并根据要用作筛选器的数据调用一个或另一个方法: