164

I'm trying to get a list of all the users from "users" table and I get the following error:

org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users]
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)

This is the code I wrote to add/get users:

public List<User> getUsers() {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    List<User> result = (List<User>) session.createQuery("from users").list();
    session.getTransaction().commit();
    return result;
}

public void addUser(User user) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();
}

public void addUser(List<User> users) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    for (User user : users) {
        session.save(user);
    }
    session.getTransaction().commit();
}

Adding users works, but when I use the getUsers function I get these error.

This is my hibernate config file:

<hibernate-configuration>
<session-factory>
    <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.default_schema">test</property>
    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

    <property name="show_sql">true</property>

    <property name="format_sql">true</property>
    <property name="hbm2ddl.auto">create-drop</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <property name="current_session_context_class">thread</property>

    <!-- Mapping files will go here.... -->

    <mapping class="model.Company" />
    <mapping class="model.Conference" />
    <mapping class="model.ConferencesParticipants" />
    <mapping class="model.ConferenceParticipantStatus" />
    <mapping class="model.ConferencesUsers" />
    <mapping class="model.Location" />
    <mapping class="model.User" />

</session-factory>

and this is my User class:

@Entity
@Table( name = "Users" )
public class User implements Serializable{

    private long userID;
    private int pasportID;
    private Company company; 
    private String name;
    private String email;
    private String phone1;
    private String phone2;
    private String password; //may be null/empty , will be kept hashed
    private boolean isAdmin;
    private Date lastLogin;

    User() {} //not public on purpose!

    public User(int countryID, Company company, String name, String email,
            String phone1, String phone2, String password, boolean isAdmin) {
        this.pasportID = countryID;
        this.company = company;
        this.name = name;
        this.email = email;
        this.phone1 = phone1;
        this.phone2 = phone2;
        this.password = password;
        this.isAdmin = isAdmin;
    }

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    public long getUserID() {
        return userID;
    }
    public void setUserID(long userID) {
        this.userID = userID;
    }
    ...    
}

Any idea why I get this error?

Gray
  • 115,027
  • 24
  • 293
  • 354
Blue
  • 1,889
  • 4
  • 16
  • 16
  • 1
    Related to: http://stackoverflow.com/questions/14446048/hibernate-table-not-mapped-error – Gray Jul 20 '16 at 15:48

23 Answers23

347

In the HQL , you should use the java class name and property name of the mapped @Entity instead of the actual table name and column name , so the HQL should be :

List<User> result = session.createQuery("from User", User.class).getResultList();

Update : To be more precise , you should use the entity name configured in @Entity to refer to the "table" , which default to unqualified name of the mapped java class if you do not set it explicitly.

(P.S. It is @javax.persistence.Entity but not @org.hibernate.annotations.Entity)

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
  • 10
    So actually this is even case sensitive. so "from user" would result in the same exception – tObi Jul 11 '14 at 12:25
  • 3
    Its a part of the answer, but to solve the error I had to use the full object path like this: [...].createQuery("from gcv.metier.User as u where u.username= ?") – Raphael Oct 02 '15 at 00:13
  • I also had to use the whole path, perhaps JPA has an issue with the word "User"? I guess it is a reserved word in a few DB implementations. In fact, this issue only came up form me when I renamed that db table from **user** to **the_user** (part of fixing another issue) before that JPA was fine. – Michael Coxon Jun 16 '18 at 22:08
  • 1
    can you pls update list() to getResultList() as the former is deprecated? – Durja Apr 18 '19 at 09:31
  • I got this: `method createQuery in interface org.hibernate.SharedSessionContract cannot be applied to given types; [ERROR] required: java.lang.String`. It does not like `MyObject.class`. – mercury Apr 26 '22 at 05:45
37

For example: if your bean class name is UserDetails the query would be

Query query = entityManager. createQuery("Select UserName from UserDetails");

You don't use the table name from the database but the class name of bean.

jmizv
  • 1,172
  • 2
  • 11
  • 28
Kumaresan Perumal
  • 1,926
  • 2
  • 29
  • 35
12

Just to share my finding. I still got the same error even if the query was targeting the correct class name. Later on I realised that I was importing the Entity class from the wrong package.

The problem was solved after I change the import line from:

import org.hibernate.annotations.Entity;

to

import javax.persistence.Entity;
Iwan Satria
  • 1,903
  • 1
  • 19
  • 22
10

Added @TABLE(name = "TABLE_NAME") annotation and fixed. Check your annotations and hibernate.cfg.xml file. This is the sample entity file that works:

import javax.persistence.*;

@Entity
@Table(name = "VENDOR")
public class Vendor {

    //~ --- [INSTANCE FIELDS] ------------------------------------------------------------------------------------------
    private int    id;
    private String name;

    //~ --- [METHODS] --------------------------------------------------------------------------------------------------
    @Override
    public boolean equals(final Object o) {    
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final Vendor vendor = (Vendor) o;

        if (id != vendor.id) {
            return false;
        }

        if (name != null ? !name.equals(vendor.name) : vendor.name != null) {
            return false;
        }

        return true;
    }

    //~ ----------------------------------------------------------------------------------------------------------------
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    public int getId() {
        return id;
    }

    @Basic
    @Column(name = "NAME")
    public String getName() {

        return name;
    }

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

    public void setName(final String name) {    
        this.name = name;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}
vvator
  • 168
  • 2
  • 11
Fırat Küçük
  • 5,613
  • 2
  • 50
  • 53
9

There is possibility you forgot to add mapping for created Entity into hibernate.cfg.xml, same error.

Augustas
  • 1,167
  • 21
  • 31
9

org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users]

This indicates that hibernate does not know the User entity as "users".

@javax.persistence.Entity
@javax.persistence.Table(name = "Users")
public class User {

The @Table annotation sets the table name to be "Users" but the entity name is still referred to in HQL as "User".

To change both, you should set the name of the entity:

// this sets the name of the table and the name of the entity
@javax.persistence.Entity(name = "Users")
public class User implements Serializable{

See my answer here for more info: Hibernate table not mapped error

Community
  • 1
  • 1
Gray
  • 115,027
  • 24
  • 293
  • 354
7

Some Linux based MySQL installations require case sensitive. Work around is to apply nativeQuery.

@Query(value = 'select ID, CLUMN2, CLUMN3 FROM VENDOR c where c.ID = :ID', nativeQuery = true)
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Rajkumar
  • 172
  • 2
  • 3
6

Also make sure that the following property is set in your hibernate bean configuration:

<property name="packagesToScan" value="yourpackage" />

This tells spring and hibernate where to find your domain classes annotated as entities.

jrreid
  • 81
  • 1
  • 3
3

I also was importing the wrong Entity import org.hibernate.annotations.Entity; It should be import javax.persistence.Entity;

David Yee
  • 3,515
  • 25
  • 45
Ratheesh K
  • 111
  • 1
  • 5
3

Also check that you added the annotated class using:

new Configuration().configure("configuration file path").addAnnotatedClass(User.class)

That always wasted my time when adding a new table in the database using Hibernate.

Gherbi Hicham
  • 2,416
  • 4
  • 26
  • 41
3

I was getting the same error while Spring with hibernate..I was using "user" in the lowercase in my createQuery statement and my class was User..So changed it to User in my query and problem was solved.

Query before:

Query query= em.createQuery("select u from user u where u.username=:usr AND u.password=:pass",User.class);

Query after:

Query query= em.createQuery("select u from User u where u.username=:usr AND u.password=:pass",User.class);
Sociopath
  • 13,068
  • 19
  • 47
  • 75
3

Lets say, your Java Classname is User and your database table name is users. So you annotate the class with @Table(name = "users"). Fine. No problem. Now in your query you don't write like SELECT .... FROM users (DO NOT WRITE the table name). You will write SELECT .... FROM User (WRITE the class name).

Problem Solved!

1

I got this issue when i replaced old hibernate-core library with hibernate-core-5.2.12. However all my configuration was ok. And i fixed this issue by creating sessionfactory this way:

private static SessionFactory buildsSessionFactory() {
    try {
        if (sessionFactory == null) {
            StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                    .configure("/hibernate.cfg.xml").build();
            Metadata metaData = new MetadataSources(standardRegistry)
                    .getMetadataBuilder().build();
            sessionFactory = metaData.getSessionFactoryBuilder().build();
        }
        return sessionFactory;
    } catch (Throwable th) {

        System.err.println("Enitial SessionFactory creation failed" + th);

        throw new ExceptionInInitializerError(th);

    }
}

Hope it helps someone

Lakhan Sharma
  • 1,741
  • 1
  • 12
  • 19
1

In your Query you have to use class name(User) not table name(users) so your query is "from User"

1

I recommend this pattern:

@Entity(name = User.PERSISTANCE_NAME)
@Table(name = User.PERSISTANCE_NAME )
public class User {    
    static final String PERSISTANCE_NAME = "USER";

    // Column definitions here

}
Jonas Gröger
  • 1,558
  • 2
  • 21
  • 35
1

In a Spring project: I typed wrong hibernate.packagesToScan=com.okan.springdemo.entity and got this error. Now it's working well.

menoktaokan
  • 346
  • 3
  • 13
0

You must type in the same name in your select query as your entity or class(case sensitive) . i.e. select user from className/Entity Name user;

0

with org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users], you are trying to select from the users table. But you are annotating your class with @Table( name = "Users" ). So either use users, or Users.

xmen-5
  • 1,806
  • 1
  • 23
  • 44
0

If you are using xml configuration, you'll need something like the following in an applicationContext.xml file:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" lazy-init="default" autowire="default" dependency-check="default">
<property name="dataSource">
  <ref bean="dataSource" />
</property>
<property name="annotatedClasses">
  <list>
    <value>org.browsexml.timesheetjob.model.PositionCode</value>
  </list>
0

I also came across this issue while using the Quarkus microservice framework:

public class SomeResource {

  @GET
  @RolesAllowed({"basic"})
  public Response doSomething(@Context SecurityContext context) {
    // ...
  }
}

// this will generate an QuerySyntax exception, as the authorization module
// will ignore the Entity annotation and use the class name instead.
@Entity(name = "users")
@UserDefinition
public class User {
  // ...
}

// do this instead
@Entity
@Table(name = "users")
@UserDefinition
public class User {
  // ...
}
0
    <!-- Rest Repositories Web Dependency -->
    <!-- https://docs.spring.io/spring-data/rest/docs/current/reference/html/#install-chapter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 28 '23 at 09:26
0

This problem can also arise if there are two classes with the same name in different packages and Hibernate can complain unlsess you specify the full package name in the query

user1708042
  • 1,740
  • 17
  • 20
0

Are you using persistence.xml for configuring hibernate? Well, this was my case and I had to scratch my head while browsing through tons of forums and stackoverflow posts for one hour before realizing I need to add my newly created entity to persistence.xml.

<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="my_persistence_unit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <class>entityclass1</class>
        <class>entityclass2</class>
<!--        Add your class heere    -->

        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/"/>
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
            <property name="javax.persistence.jdbc.user" value=""/>
            <property name="javax.persistence.jdbc.password" value=""/>

            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.physical_naming_strategy" value="org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy"/>
        </properties>
    </persistence-unit>
</persistence>
Casio991ms
  • 37
  • 8