When developing Java applications that use Hibernate/JPA, you may encounter this error:

Unknown database ‘dbname’

This error usually occurs when you import a project to your computer and the database name it uses is different than the database name on your computer. You change the database name but it doesn’t solve the problem.

The exception stack trace would look like this:

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
	at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
	...
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
	at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
	...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'bookstore'
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)	
	...

The real cause of the error is Unknown database ‘bookstore’. The database name is configured in the persistence.xml file like this:

<?xml version="1.0" encoding="UTF-8"?>
<persistence...>

	<persistence-unit name="BookStore">
		<properties>
			<property name="javax.persistence.jdbc.url"
				value="jdbc:mysql://localhost:3306/bookstoredb" />
			...
		</properties>
	</persistence-unit>

</persistence>

You check the database name in the JDBC URL and it is absolutely correct – But the error still occurs. It still mentions the old database name. You don’t understand why - spending hours to find what went wrong but you’re totally lost!

I was in such situation and nearly got upset about that problem. Fortunately, I figured out that there’s another location in which the database name is used. It is in the model classes, for example:

@Entity
@Table(name = "category", catalog = "bookstore"...)
public class Category implements java.io.Serializable {
	...
}

Here, you can see the catalog attribute of the @Table annotation refers to the database name. Voila!

This code maybe generated by Hibernate Reverse Engineering tool, so you don’t notice. So to solve the error, you have to either:

  • Update the database name in the catalog attribute in the model classes, or
  • Delete all the catalog attribute in the model classes.

Then the error Unknown database error will be solved.


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment