28

this is the error

org.hibernate.hql.ast.QuerySyntaxException: Payment is not mapped [select p from Payment p]

I don't understand how come this error is thrown, the class should be mapped as I will show you briefly. I have a very basic config, like this one: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/ch01.html

I have tried to add the mapping definition into hibernate.cfg.xml and I have also tried to add it programmatically. Neither of them worked. Could anybody tell me what am I missing here? (it is not the first time I put together a Hibernate project)

this is the hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/paymentsdatabase</property>
    <property name="hibernate.connection.username">xxx</property>
    <property name="hibernate.connection.password">xxx</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>

    <property name="hibernate.hbm2ddl.auto">create</property>

    <!--  <mapping class="com.lsyh.swati.zk.model.Payment"/> -->
  </session-factory>
</hibernate-configuration>

the database connection is working fine, I have tested that

this is the static initializer in my HibernateUtil

static {
    try {

        // Create the SessionFactory from standard (hibernate.cfg.xml) 
        // config file.
        sessionFactory = new AnnotationConfiguration()
            .addPackage("com.lsyh.swati.zk.model")
            .addAnnotatedClass(Payment.class)
            .configure().buildSessionFactory();
    } catch (Throwable ex) {
        // Log the exception. 
        System.err.println("Initial SessionFactory creation failed. " + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

and this is where I use the sessionFactory in the PaymentIODb class:

public static List<Payment> readDataFromDb(){
        StatelessSession session = StoreHibernateUtil.getSessionFactory().openStatelessSession();
        Query query = session.createQuery("select p from Payment p");
        List<Payment> payments = query.list();
        session.close();
        return payments;
}    

this is the stack trace

org.hibernate.hql.ast.QuerySyntaxException: Payment is not mapped [select p from Payment p]
    at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
    at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)
    at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70)
    at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:255)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2945)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281)
    at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229)
    at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228)
    at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160)
    at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
    at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
    at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
    at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
    at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
    at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
    at com.lsyh.swati.zk.controller.PaymentIODb.readDataFromDb(PaymentIODb.java:35)
    at com.lsyh.swati.zk.controller.PaymentIODb.resolveVariable(PaymentIODb.java:20
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
user1100478
  • 291
  • 1
  • 3
  • 4

7 Answers7

32

I'd expect one of two things to be the reason:

  1. either you don't have Payment listed in your hibernat.cfg.xml or where ever you config your mapped classes.

  2. another reason might be the confusion between javax...Entity and org.hibernate....Entity. Make sure you use the first one.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • Well, Sir, the @Entity annotation _was_ actually org.hibernate... I have changed it to javax.persistence.Entity. The result list is still empty though. it is empty because the table name (and also the column names) are not translated from camelCase to camel_case (underlines as in the database) . If you could hint me on this one ... Thanks anyway – user1100478 Dec 15 '11 at 18:53
  • 3
    you can simply use the @Table(name="camel_case") on your entity class – Sebastien Lorber Dec 15 '11 at 22:47
  • Do I have to list my annotated model classes in hibernate.cfg.xml or is this use case only when you have xml mapping? – Johnny Bra Jun 22 '20 at 19:54
30

Instead of

Query query = session.createQuery("select p from Payment p");

try this

Query query = session.createQuery("select p from " + Payment.class.getName() + " p");
mprabhat
  • 20,107
  • 7
  • 46
  • 63
  • 1
    Tahnks, this eliminates the error! Although the returned list is empty and there is a WARN in the log: `2011-12-15 19:39:39,246 [http-8080-2] WARN org.hibernate.hql.QuerySplitter - no persistent classes found for query class: select p from com.lsyh.swati.zk.model.Payment p` – user1100478 Dec 15 '11 at 18:43
  • 1
    check in your Payment class Entity should be coming from javax.persistence.Entity and Table should be coming from javax.persistence.Table. Dont use the annotation from hibernate package – mprabhat Dec 15 '11 at 18:49
  • Thanks for your answer, I accepted Jens' answer because that had the same result but it made me somewhat clear what is the problem. Thanks anyway! – user1100478 Dec 15 '11 at 18:56
  • 3
    Could you give me an explanation why this works. I met the same issue and got my code work by using this solution? – Kyleinincubator Apr 06 '13 at 00:13
  • Hats off to you! I was breaking my head on this for hours. This is a simple solution, every hibernate project I ever worked with had this technique and yet no one documented a solution for this problem so well. – Ace Mar 10 '14 at 21:10
  • 1
    Can any body explain why this works? It solve my problem when using select statement , though I directly use entity name at delete statement works fine. – JaskeyLam Aug 11 '15 at 11:08
  • +, It help me too. Please present any explanation. – Sild Apr 29 '16 at 22:48
3

uncomment the commented mapping code in hibernate.cfg.xml config file

<!--  <mapping class="com.lsyh.swati.zk.model.Payment"/> -->

change it to

<mapping class="com.lsyh.swati.zk.model.Payment"/>

for more information refer this link

http://www.javabeat.net/tips/112-configure-mysql-database-with-hibernate-mappi.html

sethupathi.t
  • 502
  • 2
  • 6
1

Your entity bean is not getting registered i guess. Set proper root package name of your entity beans in packagesToScan property. Also check your @Table(name="name_of_your_table").

1

Although accepted answer is correct, would like to add context to the first part of the answer.

Inside of your config.java (or whatever you have named your application configuration file in packages), ensure you have properly configured your entityScan:

package com.example.config;

import org.springframework.boot.autoconfigure.domain.EntityScan;

@EntityScan("com.example.entities")

However, if you like our team have moved your objects into their own packages, you may want to allow for a scan of all package folders:

@EntityScan("com.example.*")

Now that not all entities are in the entities folder specifically.

Mindsect Team
  • 2,311
  • 5
  • 29
  • 36
0

For me, my Class was not listed in my Persistence.xml file in the class section.

Do that to solve the ish. or wherever your classes are listed.

lordUhuru
  • 197
  • 1
  • 12
0

I had same problem , instead @Entityt mapping i I used following code for getting records private @Autowired HibernateTemplate incidentHibernateTemplate;

    List<Map<String, Object>> list = null;
            list = incidentHibernateTemplate.execute(new HibernateCallback<List<Map<String, Object>>>() {

            @Override
            public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery("SELECT * from table where appcode = :app");
                    query.setParameter("app", apptype);
                query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                return query.list();

                }
            });

I used following code for update

private @Autowired HibernateTemplate incidentHibernateTemplate;
Integer updateCount = 0;

    updateCount = incidentHibernateTemplate.execute((Session session) -> {
        Query<?> query = session
                    .createSQLQuery("UPDATE  tablename SET key = :apiurl, data_mode = :mode WHERE apiname= :api ");
          query.setParameter("apiurl", url);
          query.setParameter("api", api);
          query.setParameter("mode", mode);
            return query.executeUpdate();
        }
    );
Parameshwar
  • 856
  • 8
  • 16