我有一个Hibernate查询的问题,如下所示:
List persons = getList("FROM creator.models.Person p WHERE p.lastName="+userName);( getList(String queryString)方法只使用会话工厂执行查询。)
这是我的person类:
@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)
//etcHibernate创建的查询如下所示:
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突然被视为列名。
发布于 2012-12-11 00:27:53
您需要用单引号将参数括起来:
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();发布于 2012-12-11 00:27:38
您需要将userName放在引号中:
"FROM creator.models.Person p WHERE p.lastName='"+userName+"'";或者(哪个更好)来使用参数
发布于 2012-12-11 00:30:45
将您的hql替换为:
Query query = session.createQuery("from creator.models.Person p where p.lastName = ?")
.setParameter(0, userName);
List persons = query.list();这样还可以防止sql注入。
https://stackoverflow.com/questions/13804940
复制相似问题