Thursday, August 3, 2017

org.hibernate.exception.SQLGrammarException: could not execute query

Developers those who are working in Hibernate must have come across the above exception sometimes. It is not a big issue but certainly is a confusing one. it certainly takes your time if you are new hibernate and not observing the exception stack trace in detail. I will explain where you might be gone wrong to get the exception and how to debug it easily.

The exception itself is self explanatory. Though the exception says “ org.hibernate.exception.SQLGrammarException”, but it has nothing to do with grammar. It means there is some error in the sql statement executed by hibernate.  So where to check for the error in the sql statement?

First if you are using named query or model, please check the entity name is correctly mentioned. The entity name should be exactly same the table name in the database.  For example, we declare employee in the model class as shown below
@Table(name="employee")
Hence we should have employee table in our database. Any spelling mistake in the table name can 
throw the above exception.

Secondly in the model class check if you are using correct column names. Any incorrect column name 
could through this exception. For example @Column(name="emp_name") should match the emp_name 
column field of the associate table. If you are using hibernate-mapping  and mapping columns as shown 
in the below example, make sure the column name in the property  should match the column name in the 
table

Example  name="employeeName"  column="emp_name"/>
So the column name in the table should be emp_name. Any spelling mistake in the column name can 
through the above section. 
 

Hope this helps. Any more information and suggestion will be welcomed.

No comments:

Post a Comment