[Solved] Initial SessionFactory creation failed.org.hibernate.HibernateException: Errors in named queries

1. Reason

While working on post “Named queries in hibernate“, I encountered this error. Hibernate entity I coded was like this:

@Entity
@Table(name = "DEPARTMENT", uniqueConstraints = {
					@UniqueConstraint(columnNames = "ID"),
					@UniqueConstraint(columnNames = "NAME") })
@NamedQueries
(
	{
		@NamedQuery(name=DepartmentEntity.GET_DEPARTMENT_BY_ID, query=DepartmentEntity.GET_DEPARTMENT_BY_ID_QUERY),
		@NamedQuery(name=DepartmentEntity.UPDATE_DEPARTMENT_BY_ID, query=DepartmentEntity.UPDATE_DEPARTMENT_BY_ID_QUERY)
	}
)
public class DepartmentEntity implements Serializable {

	static final String GET_DEPARTMENT_BY_ID_QUERY = "from Department d where d.id = :id";
	public static final String GET_DEPARTMENT_BY_ID = "GET_DEPARTMENT_BY_ID"; 

	static final String UPDATE_DEPARTMENT_BY_ID_QUERY = "UPDATE Department d SET d.name=:name where d.id = :id";
	public static final String UPDATE_DEPARTMENT_BY_ID = "UPDATE_DEPARTMENT_BY_ID"; 

	//More code
}

And the error was:

Initial SessionFactory creation failed.org.hibernate.HibernateException: Errors in named queries: GET_DEPARTMENT_BY_ID, UPDATE_DEPARTMENT_BY_ID
Exception in thread "main" java.lang.ExceptionInInitializerError
	at hibernate.test.HibernateUtil.buildSessionFactory(HibernateUtil.java:22)
	at hibernate.test.HibernateUtil.<clinit>(HibernateUtil.java:10)
	at hibernate.test.TestHibernateNamedQuery.main(TestHibernateNamedQuery.java:13)
Caused by: org.hibernate.HibernateException: Errors in named queries: GET_DEPARTMENT_BY_ID, UPDATE_DEPARTMENT_BY_ID
	at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:364)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1291)
	at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:915)
	at hibernate.test.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
	... 2 more
Random exceptions
Random exceptions

2. Solution

The problem is with the entity names in most of the cases. Actually, we have to follow HQL syntax, and it tells us to use “entity name” in the query. So the correct queries are:

static final String GET_DEPARTMENT_BY_ID_QUERY = "from DepartmentEntity d where d.id = :id";
static final String UPDATE_DEPARTMENT_BY_ID_QUERY = "UPDATE DepartmentEntity d SET d.name=:name where d.id = :id";

Note that I replaced “Department” with “DepartmentEntity”. Now everything works fine.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “[Solved] Initial SessionFactory creation failed.org.hibernate.HibernateException: Errors in named queries”

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.