Get list of objects with JPA and Hibernate

Asked

Viewed 4,196 times

4

I’d like some help. In my code the method of entering the object in the database is working, however when trying to get a list of objects stored in the database, I get the error that my table is not mapped. Below are the classes, xml and error log.

Pessoa.java

@Entity
@Table(name="pessoas")
public class Pessoa {
    private Long id;
    private Integer idade;
    public static String NAME = "name";
    protected SimpleStringProperty name = new SimpleStringProperty("");

    @Id
    @GeneratedValue
    @Column(name="pessoas_id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name="pessoas_nome")
    public String getNome() {
        return name.get();
    }

    public void setNome(String nome) {
        this.name.set(nome);
    }

    @Column(name="pessoas_idade")
    public Integer getIdade() {
        return idade;
    }

    public void setIdade(Integer idade) {
        this.idade = idade;
    }
}

Personal.java.

public class PessoaDAO {
    private EntityManager manager;
    private EntityManagerFactory factory;

    public PessoaDAO() {

        factory = Persistence.createEntityManagerFactory("wehave");
        manager = factory.createEntityManager();
    }

    public void insert(Pessoa pessoa) {
        try {

            manager.persist(pessoa);
            manager.getTransaction().begin();
            manager.getTransaction().commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            manager.getTransaction().rollback();
        }
    }

    public void remove(Pessoa pessoa) {
        try {
            manager.getTransaction().begin();
            manager.remove(pessoa);
            manager.getTransaction().commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            manager.getTransaction().rollback();
        }

    }

    public List<Pessoa> getList()
    {
        Query query = manager.createQuery("SELECT e FROM pessoas e");
        List<Pessoa> pessoas = query.getResultList();
        return pessoas;
    }

}

Java test.

public class Teste {
        public static void main(String[] args) {
            Pessoa p = new Pessoa();

            p.setNome("Gabriel");
            p.setIdade(19);

            Pessoa p2 = new Pessoa();

            p2.setNome("José");
            p2.setIdade(72);

            Pessoa p3 = new Pessoa();

            p3.setNome("Maria");
            p3.setIdade(27);

            Pessoa p4 = new Pessoa();

            p4.setNome("Rodolfo");
            p4.setIdade(16);

            PessoaDAO dao = new PessoaDAO();
            dao.insert(p4);
            dao.insert(p3);
            dao.insert(p2);
            dao.insert(p);

            List<Pessoa> pessoas = dao.getList();

            for (int a=0; a<pessoas.size(); a++)
            {
                System.out.println(pessoas.get(a).getNome());
            }

        }
    }

pesistence.xml

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com    /xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="wehave" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>model.Pessoa</class>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/wehavescience" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="xxxxxx" />

        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="false" />
        <property name="hibernate.use_sql_comments" value="false" />
        <property name="hibernate.jdbc.wrap_result_sets" value="false" />
        <property name="hibernate.hibernate.cache.use_query_cache" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
    </properties>
</persistence-unit>

STACKTRACE

Sep 04, 2014 6:50:31 pm org.hibernate.ejb.Hibernatepersistence logDeprecation WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead. Sep 04, 2014 6:50:31 pm org.hibernate.ejb.Hibernatepersistence logDeprecation WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead. Sep 04, 2014 6:50:31 pm org.hibernate.ejb.Hibernatepersistence logDeprecation WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead. Sep 04, 2014 6:50:31 PM org.hibernate.jpa.internal.util.Loghelper logPersistenceUnitInformation INFO: HHH000204: Persistenceunitinfo Processing [ name: wehave ...] Sep 04, 2014 6:50:31 pm org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.3.6.Final} Sep 04, 2014 6:50:31 PM org.hibernate.cfg.Environment INFO: HHH000206: Hibernate.properties not found Sep 04, 2014 6:50:31 pm org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode Provider name : javassist Sep 04, 2014 6:50:32 PM org.hibernate.Annotations.common.Reflection.java.Javareflectionmanager INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final} Sep 04, 2014 6:50:32 PM org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl configure WARN: HHH000402: Using Hibernate built-in Connection pool (not for Production use!) Sep 04, 2014 6:50:32 PM org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl buildCreator INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/wehavescience] Sep 04, 2014 6:50:32 PM org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl buildCreator INFO: HHH000046: Connection properties: {user=root, password=***} Sep 04, 2014 6:50:32 PM org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl buildCreator INFO: HHH000006: Autocommit mode: false Sep 04, 2014 6:50:32 PM org.hibernate.engine.jdbc.Connections.internal.Drivermanagerconnectionproviderimpl configure INFO: HHH000115: Hibernate Connection pool size: 20 (min=1) Sep 04, 2014 6:50:33 pm org.hibernate.dialect.Dialect INFO: HHH000400: Using dialect: org.hibernate.dialect.Mysql5innodbdialect Sep 04, 2014 6:50:33 PM org.hibernate.hql.internal.Ast.Astquerytranslatorfactory INFO: HHH000397: Using Astquerytranslatorfactory Sep 04, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.Schemaupdate execute INFO: HHH000228: Running hbm2ddl schema update Sep 04, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.Schemaupdate execute INFO: HHH000102: Fetching database Metadata Sep 04, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.Schemaupdate execute INFO: HHH000396: Updating schema Sep 04, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000261: Table found: wehavescience.people Sep 04, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000037: Columns: [People, People, People, People] Sep 04, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000108: Foreign Keys: [] Sep 04, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.Tablemetadata INFO: HHH000126: Indexes: [Primary] Sep 04, 2014 6:50:34 PM org.hibernate.tool.hbm2ddl.Schemaupdate execute INFO: HHH000232: Schema update complete Hibernate: Insert into people (persons_age, persons_name) values (?, ?) Hibernate: Insert into people (persons_age, persons_name) values (?, ?) Hibernate: Insert into people (persons_age, persons_name) values (?, ?) Hibernate: Insert into people (persons_age, persons_name) values (?, ?) Exception in thread "main" java.lang.Illegalargumentexception: org.hibernate.hql.internal.Ast.Querysyntaxexception: people is not Mapped [from people] at org.hibernate.jpa.spi.Abstractentitymanagerimpl.Convert(Abstractentitymanagerimpl.java:1750) at org.hibernate.jpa.spi.Abstractentitymanagerimpl.Convert(Abstractentitymanagerimpl.java:1677) at org.hibernate.jpa.spi.Abstractentitymanagerimpl.Convert(Abstractentitymanagerimpl.java:1683) at org.hibernate.jpa.spi.Abstractentitymanagerimpl.createQuery(Abstractentitymanagerimpl.java:331) at controller.PersonDAO.getList(Personal.java:48) at app.Teste.main(Test.java:38) Caused by: org.hibernate.hql.internal.Ast.Querysyntaxexception: people is not Mapped [from people] at org.hibernate.hql.internal.Ast.QuerySyntaxException.generateQueryException(Querysyntaxexception.java:96) at org.hibernate.Queryexception.wrapWithQueryString(Queryexception.java:120) at org.hibernate.hql.internal.Ast.QueryTranslatorImpl.doCompile(Querytranslatorimpl.java:234) at org.hibernate.hql.internal.Ast.QueryTranslatorImpl.Compile(Querytranslatorimpl.java:158) at org.hibernate.engine.query.spi.HQLQueryPlan.(Hqlqueryplan.java:126) at org.hibernate.engine.query.spi.HQLQueryPlan.(Hqlqueryplan.java:88) at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(Queryplancache.java:167) at org.hibernate.Internal.AbstractSessionImpl.getHQLQueryPlan(Abstractsessionimpl.java:301) at org.hibernate.Internal.AbstractSessionImpl.createQuery(Abstractsessionimpl.java:236) at org.hibernate.Internal.SessionImpl.createQuery(Sessionimpl.java:1800) at org.hibernate.jpa.spi.Abstractentitymanagerimpl.createQuery(Abstractentitymanagerimpl.java:328) ... 2 more Caused by: org.hibernate.hql.internal.Ast.Querysyntaxexception: people is not Mapped at org.hibernate.hql.internal.Ast.util.Sessionfactoryhelper.requireClassPersister(Sessionfactoryhelper.java:189) at org.hibernate.hql.internal.Ast.tree.Fromelementfactory.addFromElement(Fromelementfactory.java:109) at org.hibernate.hql.internal.Ast.tree.Fromclause.addFromElement(Fromclause.java:95) at org.hibernate.hql.internal.Ast.HqlSqlWalker.createFromElement(Hqlsqlwalker.java:332) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(Hqlsqqlbasewalker.java:3678) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(Hqlsqlbasewalker.java:3567) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(Hqlsqqlbasewalker.java:708) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(Hqlsqlbasewalker.java:564) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(Hqlsqlbasewalker.java:301) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(Hqlsqlbasewalker.java:249) at org.hibernate.hql.internal.Ast.QueryTranslatorImpl.Analyze(Querytranslatorimpl.java:278) at org.hibernate.hql.internal.Ast.QueryTranslatorImpl.doCompile(Querytranslatorimpl.java:206) ... 10 more

2 answers

3


You should not use, in HQL, the name of your table but the name of the class. Try this:

Query query = manager.createQuery("FROM Pessoa");

If you want to know more about HQL take a look here: Chapter 15. HQL: The Hibernate Query Language

  • That’s right... thank you!

  • Very good! Thanks too! rs

1

Two things I noticed: 1° - change the persistence.xml to the file you are using for this:

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

The package ejb Provider is depreciated.

2° - in its Insert() method call first Begin() and then persist().

public void insert(Pessoa pessoa) {
    try {            
        manager.getTransaction().begin();
        manager.persist(pessoa);
        manager.getTransaction().commit();
    } catch (Exception ex) {
        ex.printStackTrace();
        manager.getTransaction().rollback();
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.