Hibernate error - QuerySyntaxException: users is not mapped [from users]

JavaHibernate

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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)

Solution 2 - Java

For example: your bean class name is UserDetails

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

You do not give your table name on the Db. you give the class name of bean.

Solution 3 - Java

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;

Solution 4 - Java

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;
    }
}

Solution 5 - Java

> 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: https://stackoverflow.com/questions/14446048/hibernate-table-not-mapped-error/38484695#38484695

Solution 6 - Java

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

Solution 7 - Java

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)

Solution 8 - Java

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.

Solution 9 - Java

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

Solution 10 - Java

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.

Solution 11 - Java

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);

Solution 12 - Java

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

Solution 13 - Java

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

}

Solution 14 - Java

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

Solution 15 - Java

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

Solution 16 - Java

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;

Solution 17 - Java

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.

Solution 18 - Java

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>

Solution 19 - Java

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 {
  // ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlueView Question on Stackoverflow
Solution 1 - JavaKen ChanView Answer on Stackoverflow
Solution 2 - JavaKumaresan PerumalView Answer on Stackoverflow
Solution 3 - JavaIwan SatriaView Answer on Stackoverflow
Solution 4 - JavaFırat KÜÇÜKView Answer on Stackoverflow
Solution 5 - JavaGrayView Answer on Stackoverflow
Solution 6 - JavaAugustasView Answer on Stackoverflow
Solution 7 - JavaRajkumarView Answer on Stackoverflow
Solution 8 - JavajrreidView Answer on Stackoverflow
Solution 9 - JavaRatheesh KView Answer on Stackoverflow
Solution 10 - JavaGherbi HichamView Answer on Stackoverflow
Solution 11 - JavaHimanshu ShuklaView Answer on Stackoverflow
Solution 12 - JavaLakhan SharmaView Answer on Stackoverflow
Solution 13 - JavaJonas GrögerView Answer on Stackoverflow
Solution 14 - JavamenoktaokanView Answer on Stackoverflow
Solution 15 - Javasami gharbiView Answer on Stackoverflow
Solution 16 - JavaVipul ThakurView Answer on Stackoverflow
Solution 17 - Javaxmen-5View Answer on Stackoverflow
Solution 18 - JavaGeoffrey RitcheyView Answer on Stackoverflow
Solution 19 - JavaNathan SimpsonView Answer on Stackoverflow