JPA Spring EntityManager的这种奇怪行为的解决方案是什么?

时间:2013-05-08 08:10:29

标签: java spring hibernate jpa maven-3

我正在开发一个带有JPA的Web应用程序,Maven和Hibernate Framework下的Spring MVC,我有这个列表方法:

@Transactional
    public List<Person> list() throws DatabaseException {
        Person person = new Person("Andrea Patricelli", "a@live.it", "3204524292");
        entityManager.persist(person);
        Person p = entityManager.find(Person.class, "Andrea Patricelli");
        System.out.println(" FOUND: -------->" + p.getName() + " " + p.getEmail() + " " + p.
                getCellPhoneNumber());
        Query query = entityManager.createQuery("FROM Persons");
        List<Person> resultList = query.getResultList();
        System.out.println("ECCO UN ELEMENTO DELLA LISTA: ------->" + resultList.iterator().next().getName());
        for (Person next : resultList) {
            System.out.println("next person: " + next);
        }
        return resultList;
    }

当我运行我的例子时,我得到了这个堆栈跟踪:

[INFO] [talledLocalContainer] FOUND: -------->Andrea Patricelli andreapatricelli@gmail.com 0854312119
[INFO] [talledLocalContainer] 08 mag 2013;10:03:10 DEBUG o.h.h.i.ast.QueryTranslatorImpl - parse() - HQL: FROM Persons
[INFO] [talledLocalContainer] 08 mag 2013;10:03:10 DEBUG o.h.h.i.ast.QueryTranslatorImpl - --- HQL AST ---
[INFO] [talledLocalContainer]  \-[QUERY] Node: 'query'
[INFO] [talledLocalContainer]     \-[SELECT_FROM] Node: 'SELECT_FROM'
[INFO] [talledLocalContainer]        \-[FROM] Node: 'FROM'
[INFO] [talledLocalContainer]           \-[RANGE] Node: 'RANGE'
[INFO] [talledLocalContainer]              \-[IDENT] Node: 'Persons'
[INFO] [talledLocalContainer] 
[INFO] [talledLocalContainer] 08 mag 2013;10:03:10 DEBUG o.h.hql.internal.ast.ErrorCounter - throwQueryException() : no errors
[INFO] [talledLocalContainer] 08 mag 2013;10:03:11 DEBUG o.h.h.i.antlr.HqlSqlBaseWalker - select << begin [level=1, statement=select]
[INFO] [talledLocalContainer] 08 mag 2013;10:03:11 DEBUG o.h.e.t.spi.AbstractTransactionImpl - rolling back
[INFO] [talledLocalContainer] 08 mag 2013;10:03:11 DEBUG o.h.e.t.i.jdbc.JdbcTransaction - rolled JDBC Connection
[INFO] [talledLocalContainer] 08 mag 2013;10:03:11 DEBUG o.h.e.t.i.jdbc.JdbcTransaction - re-enabling autocommit
[INFO] [talledLocalContainer] 08 mag 2013;10:03:11 DEBUG o.h.e.j.i.LogicalConnectionImpl - Releasing JDBC connection
[INFO] [talledLocalContainer] 08 mag 2013;10:03:11 DEBUG o.h.e.j.i.LogicalConnectionImpl - Released JDBC connection

我希望这段代码打印出我数据库中所有人员的列表(3人),好像查询格式不好而且有错误,但我没有错误!或者另一方面,我在理解如何使用Hibernate进行查询时遇到了错误...

1 个答案:

答案 0 :(得分:1)

这一行给出了问题:

Query query = entityManager.createQuery("FROM Persons");

由于您的实体类名称为Person,并且您在查询中提供了Persons,因此其行为很奇怪。

Query query = entityManager.createQuery("FROM Person"); // This should fetch everything now, as expected!