Home > database >  Spring Data JPA creates two tables after renaming entity
Spring Data JPA creates two tables after renaming entity

Time:04-01

I'm using Spring Boot 2.6.4 and Java 17. And I previously had an Entity called BlogPostComment but recently decided that just Comment is more concise. I don't have a data.sql file to explicitly create tables and let Hibernate handle all the database operations for me. So I'm expecting that the table previously named blog_post_comment would be renamed as comment. However, when I rerun my application after renaming the entity, Hibernate creates two tables blog_post_comment and comment instead of just the latter.

Before renaming:

@Entity
public class BlogPostComment { ... }

After renaming:

@Entity
public class Comment { ... }

I've tried adding @Table(name = "comment") annotation to this entity, but Hibernate created the table with the old name all the same. And I've also tried invalidating IntelliJ IDEA caches, still did not solve this problem. Please help me identify the cause of this error, thank you.

CodePudding user response:

It is possible that your hibernate.hbm2ddl.auto property in application.properties is set to none . What none does is that no action is performed. The schema will not be generated. Hence your changes will appear as a new table in your database. What you should do then is to set the property to update and then run the application. What update does is that the database schema will be updated by comparing the existing database schema with the entity mappings.

PS: If no property is defined, the default property is none. You should add the property and set to update

CodePudding user response:

I strongly doubt that Hibernate creates a blog_post_comment table after you renamed the entity. I suspect this is just still around from the previous run.

Hibernate (or any other JPA implementation) does not know about you renaming the entity. It has no knowledge what so ever about the entities present during the last start of the application. Therefore it doesn't know that there is a relationship between the existing blog_post_comment table in the database and the not yet present comment table it is about to create.

When Hibernate "updates" a schema it checks if a required table already exists and if so it modifies it to match what is required by the entities. But even then it won't rename columns, it would just create new ones.

In generally you should use Hibernates schema creation feature only during development and never for actually deploying a schema into production or even worse, updating a schema in production. For this you should use specialised tools like Flyway or Liquibase which exist for exactly this purpose.

  • Related