2

I am working on a project in Java (using Spring Boot, Thymeleaf, Hibernate, JPA, MySql). Every time I create a new Model Class, I have to create a table in the database or if I make any change in the Model class I have to alter the table by myself. Is there any way to avoid this database related stuff. For example I will make Model classes and declare their relationships my Database tables will be generated automatically. In future if I make any changes to my classes they will be applied to the database automatically without loosing any data.

Previously I worked on PHP, Laravel. There all I needed to do is 1) run command php artisan make:migration create_posts_table, 2) declare columns like $table->string('title');, $table->foreign('user_id')->references('id')->on('users'); and then 3) run command php artisan migrate. That's it. No SQL scripts needed. I was wondering if Java, Spring has something like this.

Partho63
  • 3,117
  • 2
  • 21
  • 39
  • 2
    Actually I think thats bad practice to have database be generated automatically, simply because you have no/limited control over constraint names. Also when a change goes into production, you can only be sure, that the database won't be damaged in any way, if you do it manually – XtremeBaumer Aug 01 '19 at 08:15
  • 1
    Also [this answer](https://stackoverflow.com/a/42147995/7109162) explains what exactly `spring.jpa.hibernate.ddl-auto=update` does – XtremeBaumer Aug 01 '19 at 08:17
  • @XtremeBaumer Thanks. I have seen this answer before. But it is not recommended to use in production. That's why I was looking for other options. So if I use `spring.jpa.hibernate.ddl-auto=update` in development and remove from the production, then some modification is done on the project how the modification can be applied to the production part? – Partho63 Aug 01 '19 at 08:42

3 Answers3

2

Sure you can do it.

Use spring.jpa.hibernate.ddl-auto=update in your application.properties.

You can also use more advanced tools like https://www.liquibase.org/

Andrzej Jaromin
  • 269
  • 2
  • 6
1

Ideal way

spring.jpa.hibernate.ddl-auto=none

In my opinion, the ideal way is to create one SQL file which will create the schema at the startup for us.


To let Spring Boot to create it for you

spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.ddl-auto= # DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none".

Other Possible values: create, create-drop, validate

More Detailed Explanation

Romil Patel
  • 12,879
  • 7
  • 47
  • 76
0

You can do migration using Flyway, it's similar to Laravel migration.

Add the dependency and put your migration SQL files to classpath:db/migration. Flyway will automatically check the sql files version and apply any pending migrations.

https://flywaydb.org/documentation/plugins/springboot