Ignore case sensitive for table name in JPA with Hibernate implementation

When working with JPA, one problem that you might encounter is that the table name in the database is defined in lowercase, but the entity that we declare to define the table name is uppercase or vice versa.

For example, I have a table with a table name defined as lowercase:

But the entity of this table defines table name as uppercase:

Some database systems do not have any problem with that kind of declaration, but some databases do not. As I am using MySQL database version 5.7.22 with the value of lower_case_table_names set to 0 by default, defining the table and entity as above will cause me to have problems when using. Because, with the value 0 of the lower_case_table_names, the tables in MySQL must be case sensitive, see here for more.

To see what the problem is, I will create a simple Maven project as follows:

Ignore case sensitive for table name in JPA with Hibernate implementation

Maven dependencies:

The definition of the table and entity I mentioned above.

JPA configuration file has content as follows:

For simplicity, I will write a small code to insert a record into the clazz table in the Application class as follows:

Then, if you run the application, the following error will appear:

We can modify the configuration for MySQL to set the value of the lower_case_table_names to 2, but imagine if your application must run in different environments, or you may not be able to change the configuration. So, what should we do?

To solve this problem, let edit the JPA configuration file to add a Hibernate property that allows us to ignore the case sensitive of the database system that we are running.

If you are using Hibernate version 4.x then the property is “hibernate.ejb.naming_strategy” and its value is “org.hibernate.cfg.ImprovedNamingStrategy”. Then the content of the persistence.xml file would be:

If you are using Hibernate 5.x then the property is “hibernate.physical_naming_strategy” with the value “com.huongdanjava.jpa.PhysicalNamingStrategyImpl”. The contents of the PhysicalNamingStrategyImpl class will look like this:

The contents of my persistence.xml file are as follows:

In this example, I’m using Hibernate 5. Running the application again, you will not see any errors.

Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
3Tweet about this on Twitter
Share on LinkedIn

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.