我遇到了Hibernate查询的问题,如下所示:
List persons = getList("FROM creator.models.Person p WHERE p.lastName="+userName);
(getList(String queryString)
方法只使用会话工厂执行查询。)
这是我的人类:
@Entity
@Table(name="persons")
public class Person{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name="first_name", nullable=false, updatable=true)
private String firstName;
@Column(name="last_name", nullable=false, updatable=true)
private String lastName;
/// etc
这就是表格:
CREATE TABLE persons(
id INTEGER NOT NULL AUTO_INCREMENT,
first_name CHAR(50),
last_name CHAR(50),
abbreviation CHAR(4),
PRIMARY KEY (id)
);
正在搜索名为TestName的人,我收到此消息的异常:
org.hibernate.exception.SQLGrammarException: Unknown column 'TestName' in 'where clause'
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
//etc
Hibernate创建的查询如下所示:
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select person0_.id as id8_, person0_.abbreviation as abbrevia2_8_, person0_.first_name as first3_8_, person0_.last_name as last4_8_ from persons person0_ where person0_.last_name=TestName
Dec 10, 2012 5:14:26 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
顺便说一句,搜索id(...
WHERE p.id ="3"
)可以正常工作!
我希望有人知道出了什么问题,因为对我来说查询看起来是正确的,我无法找出为什么lastName被突然看作列名。
答案 0 :(得分:3)
您需要将userName放在引号中:
"FROM creator.models.Person p WHERE p.lastName='"+userName+"'";
或者(更好)使用参数
答案 1 :(得分:3)
用你的hql替换:
Query query = session.createQuery("from creator.models.Person p where p.lastName = ?")
.setParameter(0, userName);
List persons = query.list();
这样你也可以防止sql注入。
答案 2 :(得分:2)
你需要用单引号包装你的参数:
List persons = getList("FROM creator.models.Person p WHERE p.lastName='"+userName+"'");
但使用参数化查询要好得多:
String hql = "FROM creator.models.Person p WHERE p.lastName= :userName";
Query query = session.createQuery(hql);
query.setString("userName",userName);
List results = query.list();