Error in named query: org.hibernate.hql.ast.QuerySyntaxException: table is not mapped

Posted by {"name"=>"Palash Ray", "email"=>"paawak@gmail.com", "url"=>"https://www.linkedin.com/in/palash-ray/"} on August 10, 2009 · 1 min read

I was taking advantage of the NamedQueries feature in Hibernate annotation, when suddenly I was bombed with this queer error:
ERROR - SessionFactoryImpl.(363) | Error in named query: findMaxId
org.hibernate.hql.ast.QuerySyntaxException: AccountGroup is not mapped [SELECT MAX(id) FROM AccountGroup]

My AccountGroup looks like this:

@Entity(name = "account_group")
@NamedQueries( { @NamedQuery(name = AccountGroup.NAMED_QUERY_FIND_MAX_ID, query = "SELECT MAX(acg.id) FROM AccountGroup acg") })
public class AccountGroup implements Serializable {
    private static final long serialVersionUID = 8651011772980546778L;
    public static final String NAMED_QUERY_FIND_MAX_ID = "findMaxId";
...
}

As is evident from the error message, the HQL compiler is not able to map any table to "AccountGroup". But this is strange, since I have already mapped it in my hibernate.cfg.xml. After a few minutes of futile googling, the solution dawned upon me.

Solution 1:

Include an additional annotation @Table:

@Entity
@Table(name = "account_group")
@NamedQueries( { @NamedQuery(name = AccountGroup.NAMED_QUERY_FIND_MAX_ID, query = "SELECT MAX(acg.id) FROM AccountGroup acg") })
public class AccountGroup implements Serializable {
    private static final long serialVersionUID = 8651011772980546778L;
    public static final String NAMED_QUERY_FIND_MAX_ID = "findMaxId";
...
}

Solution 2:

Modify your query to have the fully qualified class name:

@Entity(name = "account_group")
@NamedQueries( { @NamedQuery(name = AccountGroup.NAMED_QUERY_FIND_MAX_ID, query = "SELECT MAX(acg.id) FROM com.swayam.test.AccountGroup acg") })
public class AccountGroup implements Serializable {
    private static final long serialVersionUID = 8651011772980546778L;
    public static final String NAMED_QUERY_FIND_MAX_ID = "findMaxId";
...
}