Java 冬眠“;其中;查询仅适用于id字段

Java 冬眠“;其中;查询仅适用于id字段,java,sql,hibernate,Java,Sql,Hibernate,我对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=Gen

我对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(
,其中p.id
=“3”
)可以正常工作


我希望有人知道出了什么问题,因为对我来说,查询看起来是正确的,我无法找出为什么lastName突然被视为列名。

您需要在用户名中加引号:

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

或者(哪一个更好)使用参数

您需要用单引号将参数括起来:

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();
将hql替换为:

    Query query = session.createQuery("from creator.models.Person p where p.lastName = ?")
       .setParameter(0, userName);
    List persons = query.list();
这样还可以防止sql注入