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

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;

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

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.


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)

Tags:

Java

Hibernate