I was taking advantage of the NamedQueries feature in Hibernate annotation, when suddenly I was bombed with this queer error:
ERROR - SessionFactoryImpl.
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.
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";
...
}
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";
...
}