Reputation: 3117
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.
Upvotes: 2
Views: 1042
Reputation: 1
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
Upvotes: 0
Reputation: 13747
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
Upvotes: 1
Reputation: 269
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/
Upvotes: 2