Whenever I try to rename a column of an entity of spring boot application and run it then a new column in the database table is added with the new name instead of updating the existing one.
For example renaming column user_id to users_id
before renaming
@Entity
@Table(name = "users")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;
private String name;
private String password;
private String email;
}
after renaming:
@Entity
@Table(name = "users")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "users_id")
private Long id;
private String name;
private String password;
private String email;
}
I want to rename the existing column name using the spring application. How can I achieve it please guide me through it.
CodePudding user response:
If you are in the development phase, the easiest solution is to do it by hand.
In production, you should limit breaking changes. If you must rollback or as soon as you have multiple instances of your service, it becomes very dangerous.
Prefer to copy your data and switch to this one. Delete your old column later (a lot).
CodePudding user response:
To create migration with flyway you can dothe following:
- Add to
application.properties
:
# tell hibernate to validate schema instead of creating it
spring.jpa.hibernate.ddl-auto=validate
# set path to flyway migrations
spring.flyway.locations=classpath:db/migration
- Add flyway dependency to
pom.xml
:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
- Add migration to
src/main/resources/db/migration
calledV1_create_user_table.sql
:
CREATE TABLE users (
user_id IDENTITY PRIMARY KEY,
name VARCHAR(255),
password VARCHAR(255),
email VARCHAR(255)
)
- When you change
user_id
tousers_id
in your entity, add another migration `V2_rename_id_column.sql:
ALTER TABLE users ALTER COLUMN user_id RENAME TO users_id;