0

我试图通过注释而不是休眠 xml 映射来处理“实体”。
我面临添加成功但检索失败的情况 - 感谢您的帮助。
型号类:

@Entity
@Table(name = "PERSON")
public class Person implements Serializable {
    private static final long serialVersionUID = -5527566248002296042L;
    @Id
    @Column(name = "ID")
    @GeneratedValue
    private Integer id;
    @Column(name = "FIRST_NAME")
    private String firstName;
    @Column(name = "LAST_NAME")
    private String lastName;
    @Column(name = "MONEY")
    private Double money;
.....setters and getters
}

弹簧配置:

<context:annotation-config />
    <context:component-scan base-package="org.spring.entity,org.spring.service" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
....
    </bean>

        <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
...
        <property name="packagesToScan">
        <list>
        <value>org.spring.entity</value>
        <value>org.spring.service</value>
        </list>
        </property>
        <property name="hibernateProperties">
...
        </property>
    </bean>

服务等级:

public void add(String firstName, String lastName, Double money) {
        // Retrieve session from Hibernate
        Session session = sessionFactory.openSession();
        try{ 
        // Create a new person
        Person person = new Person();
        person.setFirstName(firstName);
        person.setLastName(lastName);
        person.setMoney(money);

        // Save
        session.save(person);
        }
        finally{
        session.close();
        }
    }
public void edit(Integer id, String firstName, String lastName, Double money) {
        // Retrieve session from Hibernate
        Session session = sessionFactory.openSession();
        try{ 
        // Retrieve existing person via id
        Query query = session.createQuery("FROM  Person WHERE ID=?");<=FAILS HERE
        query.setInteger(0, id);
        Person person = (Person)query.list().get(0);
......
}

错误如下:

Exception in thread "main" org.hibernate.hql.internal.ast.QuerySyntaxException:
person is not mapped [from person where ID=?]
        at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClass
Persister(SessionFactoryHelper.java:180)
        at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement
(FromElementFactory.java:110)
        at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromCla
use.java:93)
        at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlW
alker.java:324)
4

1 回答 1

0

您的 HQL 错误,请这样做:

(如果有多个结果,它们可能是左右一些语法,请检查。)

Query query = session.createQuery("FROM  Person WHERE ID=:ID")
List list=query.setParameter("ID",ID).list();

或者

(如果是单一结果)

Person person =new Person ();
person =(Person ) session.get(Person .class, ID);
于 2013-08-06T05:38:47.273 回答