How to alter table by changing the entity in JPA with auto-ddl=update
Asked Answered
M

2

2

I changed the entity UserInfoEntity, variable name from 'moblie' to 'mobile', and then I restarted my server. when I looked at the table i found that the table hasn't removed the column 'moblie'. Here is my change in entity;

From this;

@Entity
@Table(name = "pe_userinfo")
public class UserInfoEntity {
    private String moblie;
}

to this;

@Entity
@Table(name = "pe_userinfo")
public class UserInfoEntity {
    private String mobile;
}
Myotonia answered 3/11, 2018 at 8:8 Comment(4)
What is "auto-dll" ? JPA has no such property. It has some properties javax.persistence.schema-generation.*. In general a JPA provider is not the most appropriate tool to handle schema upgrading ... better to use Liquibase/Flyway for thatDuckworth
Makes no sense to use Hibernate specific things when there are JPA standard equivalentsDuckworth
@BillyFrost spring.jpa.hibernate.ddl-auto it is well within JPA, no problem to access them at all.Bipropellant
Nope. It is not a JPA standard property. It is a HIBERNATE specific property. The clue is in the nameDuckworth
L
5

Use auto-ddl=create-drop to drop the faulty schema in its entirety & recreate it with fixed column value, you cannot have update schema in such manner.

Also check Hibernate: hbm2ddl.auto=update in production?, as it says, it is better to handle such cases manually by yourself rather than using Hibernate to handle such modifications on an existing schema.

Extra Idea

If you wish to save your data;

  • You can create a separate table to hold your data pe_userinfo_temp
  • deploy your product, auto-ddl will create pe_userinfo_temp
  • use jpa logic to copy data from pe_userinfo -> pe_userinfo-temp
  • drop the table pe_userinfo manually from datasource
  • fix your column in pe_userinfo, auto-ddl will create it but will be empty
  • use similar jpa logic to copy data from pe_userinfo_temp -> new pe_userinfo
  • then finally drop the pe_userinfo_temp from your source code & drop from datasource
Lilylivered answered 3/11, 2018 at 8:54 Comment(3)
it works out. But it will drop the table and delete all records which I expect to be savedMyotonia
@陈杨华 I know, there is no other way with Hibernate sadly, you can access the datasource & edit the column yourself manually.Bipropellant
I want to find a way to solve this problem like making migrations in Python through DjangoMyotonia
S
4

I assume that you're using hibernate (may be even inside spring-data-jpa) and indeed it doesn't rename the tables but creates new ones. Moreover you shouldn't use (hibernate) auto update in any more or less serious environments.

Use flyway or liquibase instead.

Successor answered 3/11, 2018 at 8:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.