3

我的 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 突然被视为列名。

4

3 回答 3

3

您需要将 userName 放在引号中:

"FROM creator.models.Person p WHERE p.lastName='"+userName+"'";

或者(更好)使用参数

于 2012-12-10T16:27:37.967 回答
3

将您的 hql 替换为:

    Query query = session.createQuery("from creator.models.Person p where p.lastName = ?")
       .setParameter(0, userName);
    List persons = query.list();

这样你也可以防止sql注入。

于 2012-12-10T16:30:44.510 回答
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();
于 2012-12-10T16:27:53.490 回答