Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot JPA: remove column on entity change

I am try to create table in MySQL database from java class using spring-boot-starter-data-jpa. It work pretty well except when I change/remove column name in java class. Here an example:

I have a class call "Staff" with 2 fields: id, name

@Id 
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "name", length = 15)
private String name;

public Staff() {
}
// some setter and getter here

When I run my project, a "Staff" table generated exactly as I want with 2 columns: id, name. The problem is if I split "name" into "firstname" and "lastname" like this:

@Id 
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "firstname", length = 15)
private String firstname;

@Column(name = "lastname", length = 15)
private String lastname;

public Staff() {
}
//some getter and setter here

The "Staff" table now contain 4 columns (id, name, firstname, lastname) instead of 3. Then I need to remove the "name" column myself. Is there anyway to get rid of it automatically?

like image 309
Lê Quang Bảo Avatar asked Jul 07 '17 03:07

Lê Quang Bảo


1 Answers

Looks like you use :

 spring.jpa.properties.hibernate.ddl-auto=update

78.1 Initialize a database using JPA

spring.jpa.generate-ddl (boolean) switches the feature on and off and is vendor independent. spring.jpa.hibernate.ddl-auto (enum) is a Hibernate feature that controls the behavior in a more fine-grained way. See below for more detail.

You can set spring.jpa.hibernate.ddl-auto explicitly and the standard Hibernate property values are none, validate, update, create, create-drop.

as you can see there is nothing new (different from hibernate)

ddl-auto=update - generate changes but it doen't drop not mapped columns . For example you can have a table with 10 columns and mapping only for 3 of them , in this case auto mode might drop them but for hibernate / jpa full mapping table-entity in not mandatory. Here is jira ticket Alter and drop columns with hbm2ddl.auto=update created Nov 2011 and now status is 'not fixed'.

If you update db often (your domain model is changed) , you can use ddl/dml tools like liquibase , flywaydb. You describe db changes in xml file , and execute tool , all changes will be apply automatically (with auto control what already modifyed before and what should be modifed now).

Just recommendation : Better use ddl tools if you don't want to guess why something is droped in production. hibernate.ddl-auto maily used for development , not for production. In production you can use none or validate - as they are safe.

like image 113
xyz Avatar answered Nov 04 '22 18:11

xyz