[java] JPA mapping: "QuerySyntaxException: foobar is not mapped..."

I've been playing around with a very simple JPA example and am trying to tweak it to an existing database. But I can't get past this error. (Below.) It just has to be some simple thing I am not seeing.

org.hibernate.hql.internal.ast.QuerySyntaxException: FooBar is not mapped [SELECT r FROM FooBar r]
  org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
  org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
  org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)

In the DocumentManager class below (a simple servlet, as that is my target goal) does two things:

  1. insert a row
  2. return all rows

The insertion works perfectly--all is good there. The problem is with the retrieval. I've tried all sorts of values for the Query q = entityManager.createQuery parameters, but no luck, and I've tried variously more explicate annotations of the class (like column types), all without success.

Please save me from myself. I'm certain it is something small. My inexperience with JPA is preventing me from going any farther.

My ./src/ch/geekomatic/jpa/FooBar.java file:

@Entity
@Table( name = "foobar" )
public class FooBar {
    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    @Column(name="id")
    private int id;

    @Column(name="rcpt_who")
    private String rcpt_who;

    @Column(name="rcpt_what")
    private String rcpt_what;

    @Column(name="rcpt_where")
    private String rcpt_where;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getRcpt_who() {
        return rcpt_who;
    }
    public void setRcpt_who(String rcpt_who) {
        this.rcpt_who = rcpt_who;
    }

    //snip...the other getters/setters are here
}

My ./src/ch/geekomatic/jpa/DocumentManager.java class

public class DocumentManager extends HttpServlet {
    private EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory( "ch.geekomatic.jpa" );

    protected void tearDown() throws Exception {
        entityManagerFactory.close();
    }

   @Override
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
       FooBar document = new FooBar();
       document.setRcpt_what("my what");
       document.setRcpt_who("my who");

       persist(document);

       retrieveAll(response);
   }

   public void persist(FooBar document) {
       EntityManager entityManager = entityManagerFactory.createEntityManager();
       entityManager.getTransaction().begin();
       entityManager.persist( document );
       entityManager.getTransaction().commit();
       entityManager.close();
   }

    public void retrieveAll(HttpServletResponse response) throws IOException {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();

        //  *** PROBLEM LINE ***
        Query q = entityManager.createQuery( "SELECT r FROM foobar r", FooBar.class );
        List<FooBar> result = q.getResultList();

        for ( FooBar doc : result ) {
            response.getOutputStream().write(event.toString().getBytes());
            System.out.println( "Document " + doc.getId()  );
        }
        entityManager.getTransaction().commit();
        entityManager.close();
    }
}

The {tomcat-home}/webapps/ROOT/WEB-INF/classes/METE-INF/persistance.xml file

<persistence xmlns="http://java.sun.com/xml/ns/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">

<persistence-unit name="ch.geekomatic.jpa">
    <description>test stuff for dc</description>

    <class>ch.geekomatic.jpa.FooBar</class>

    <properties>
        <property name="javax.persistence.jdbc.driver"   value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url"      value="jdbc:mysql://svr:3306/test" />
        <property name="javax.persistence.jdbc.user"     value="wafflesAreYummie" />
        <property name="javax.persistence.jdbc.password" value="poniesRock" />

        <property name="hibernate.show_sql"     value="true" />
        <property name="hibernate.hbm2ddl.auto" value="create" />
    </properties>

</persistence-unit>
</persistence>

The MySQL table description:

mysql> describe foobar;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| rcpt_what  | varchar(255) | YES  |     | NULL    |                |
| rcpt_where | varchar(255) | YES  |     | NULL    |                |
| rcpt_who   | varchar(255) | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

This question is related to java mysql hibernate jpa

The answer is


You have declared your Class as:

@Table( name = "foobar" )
public class FooBar {

You need to write the Class Name for the search.
from FooBar


I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation

The correct format should be

@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name 
public class FooBar{

There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as

<class>com.yourCompanyName.WhateverEntityClass</class>

In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to hibernate

Hibernate Error executing DDL via JDBC Statement How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory Disable all Database related auto configuration in Spring Boot Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] HikariCP - connection is not available Hibernate-sequence doesn't exist How to find distinct rows with field in list using JPA and Spring? Spring Data JPA and Exists query

Examples related to jpa

No converter found capable of converting from type to type How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Deserialize Java 8 LocalDateTime with JacksonMapper Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed How to beautifully update a JPA entity in Spring Data? JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory How to return a custom object from a Spring Data JPA GROUP BY query How to find distinct rows with field in list using JPA and Spring? What is this spring.jpa.open-in-view=true property in Spring Boot? Spring Data JPA and Exists query