Database table creation and updation with springboot, spring data - spring-boot

For the database schema management with spring data/hibernate, setting spring.jpa.hibernate.ddl-auto option doesn't look like a cleaner approach.
Bcoz
1) We are forced to put the credentials of a user that has permission to create and delete in the application.properties.
2) In production, relaying on spring.jpa.hibernate.ddl-auto option could lead to dataloss, if not managed carefully.
So what is the best way out there to handle the database schema management automatically in a spring boot/spring data app?
Any pointers would help.
Thanks

If you want to track each change state of database then you can use flyway
See this link how to maintain database versioning in spring-boot

In production, you should ideally set spring.jpa.hibernate.ddl-auto property as none so that no schema changes are allowed.
For the database schema management with spring data/hibernate, I would suggest you go for Liquibase, it basically is an open source database-independent library for tracking, managing and applying database schema changes.
Every change to Schema is added as a changeset using property file in Liquibase , this is for the new changes.
In order to migrate the existing database structure into Liquibase, it provides you with commands to automatically generate Changesets by reading the current database.
So using this you can generate database schema, add constraints, load data.
More info at : https://www.liquibase.org/ , Why and when Liquibase?

Related

How to set up a connection between spring boot project and PostgresSQL DB

I created a spring boot project and I link it with my DB under PgAdmin.
I've modified the application.properties correctly and created a class named "user" and its repository "userRepository" but I don't know if this will automaticly create the user table in the DB (I used annotations) or I have to create it in PgAdmin ?
Do I need to specify any controller or webController if I want to have Crud operations ? And where does the CrudRepository exists do I need to generate it and how ?
Excuse me this my first experience with spring, I will really appreciate if you guys can help me.
Thanks in advance.
For your first question:
I don't know if this will automaticly create the user table in the DB
You have several ways how to create your tables, for example with property in application.properties file
spring.jpa.hibernate.ddl-auto = [none|validate|update|create-drop]
where none means this configuration not affect existing database
update means updating changes in database
create-drop means creating all tables from scratch according your project entities classes.
You can check this documentations for additional information
https://docs.spring.io/spring-boot/docs/1.1.0.M1/reference/html/howto-database-initialization.html
59.2 Initialize a database using Hibernate
also you can check how to initialize database with existing sql scripts files in documentation above
59.3 Initialize a database using Spring JDBC
For question: Do I need to specify any controller or webController if I want to have Crud operations ? And where does the CrudRepository exists do I need to generate it and how ?
Yes you should create controllers to handle requests and repositories to work with JPA.I also suggest check tutorial first, for example this one (first in google)
https://bezkoder.com/spring-boot-jpa-crud-rest-api/

Programmatically recreate H2 database schema in SpringBoot application (not while unit testing)?

I have a SpringBoot application with in memory H2 database and Spring Data JPA.
I need to configure a #Scheduled job that drops and recreates the schema and loads it with fresh data from a file.
How can I programmatically recreate the schema in my application?
You can use database version control tool like eg Liquibase to create and maintain database schema definition as well as initial data. Than, you will be able to easily invoke database migration including drop of whole schema during applicaiton runtime. IT has some integration with Spring Boot already.
Keep in mind, that you will have to lock database access in order to execute migration - DDL is not transactional, so database will be of no use anyway during the migration process and you app can yeld many errors during that time.
If locking is not an option - you should be able to create another instance or at least separate schema in running instance, run migration against it and if everything is done, "switch" peristence context to use brand new schema (and probably remove the old one)

How can I re generate a new JPA entity(and a database table in a different database schema) for an existing jhipster project?

How can I generate an entity(and a database table) in a different schema other than the default public schema for an existing Jhipster(4.6.2) project generated with spring boot and AngularJS as the technology stack. [Database - Postgresql]
I am very interested if it is possible. Otherwise one simple way to reach that: you could try to generate the entity using the jhipster command jhipster entity <entityName> --[options] see for more details.
And customize your application to use multiple databases by following this excellent article: https://www.baeldung.com/spring-data-jpa-multiple-databases

Liquibase compare and update databases

I would like to use liquibase in my spring boot app. My requirement is that I have a dummy schema which is populated with tables every time I change the entity classes. This is done by hibernate's ddl create. There are many identical schemas to the dummy schema with data. I want those schemas to be compared with the dummy schema on update and be synced without affecting my data. How can I achieve this? I could not find a tutorial anywhere. If there is one please do give me the link.
I think this tutorial explains what your are looking for
baeldung maven liquibase plugin
In section 5.3 is a description on how you can get a changlog file with differences between two databases.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

I was working on my Spring boot app project and noticed that, sometimes there is a connection time out error to my Database on another server(SQL Server).
This happens specially when I try to do some script migration with FlyWay but it works after several tries.
Then I noticed that I didn't specify spring.jpa.hibernate.ddl-auto in my properties file. I did some research and found that it is recommended to add
spring.jpa.hibernate.ddl-auto= create-drop in development.
And change it to: spring.jpa.hibernate.ddl-auto= none in production.
But I didn't actually understand how does it really work and how does hibernate generate database schema using create-drop or none value. Can you please explain technically how does it really work, and what are recommendations for using this property in development and on a production server.
Thank you
For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.
The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.
For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.
The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.
Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.
In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.
In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.
In Spring/Spring-Boot, SQL database can be initialized in different ways depending on what your stack is.
JPA has features for DDL generation, and these can be set up to run on startup against the database. This is controlled through two external properties:
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.
Hibernate property values are: create, update, create-drop, validate and none:
create – Hibernate first drops existing tables, then creates new tables
update – the object model created based on the mappings (annotations or XML) is compared with the existing schema, and then Hibernate updates the schema according to the diff. It never deletes the existing tables or columns even if they are no more required by the application
create-drop – similar to create, with the addition that Hibernate will drop the database after all operations are completed. Typically used for unit testing
validate – Hibernate only validates whether the tables and columns exist, otherwise it throws an exception
none – this value effectively turns off the DDL generation
Spring Boot internally defaults this parameter value to create-drop if no schema manager has been detected, otherwise none for all other cases.
"spring.jpa.hibernate.ddl-auto= create-drop" means that when the server is run, the database(table) instance is created. And whenever the server stops, the database table instance is droped.
Also depending on spring.jpa.hibernate.ddl-auto the DML files feature is enabled
DDL and DML
It is worth to understand the difference between them.
Data Definition Language(DDL) - related to database schema creating
Data Manipulation Language(DML) - related to importing data
Basically there are 3 types of database schema creating(DDL) and importing data(DML):
Using Hibernate
Using Spring JDBC SQL scripts
Using high level tools like Flyway/Liquibase
This topic covers Hibernate and it's DDL (first option), but it is worth to mention Hibernate DML files feature that enabled if spring.jpa.hibernate.ddl-auto is create or create-drop
That means import.sql in the root of the classpath will be executed on startup by Hibernate. This can be useful for demos and for testing if you are careful, but probably not something you want to be on the classpath in production. It is a Hibernate feature (nothing to do with Spring).
Also here is a table that explains spring.jpa.hibernate.ddl-auto and whether the import.sql can be used depending on spring.jpa.hibernate.ddl-auto value specified:
spring.jpa.hibernate.ddl-auto
Create schema from entities
import.sql
create
true
true
update
update schema from entities
false
create-drop
true
true
validate
false
false
none
false
false
Also some extra information about different types of DDL amd DML can be found in Spring docs
For the Propertie of JPA/Hibernate
spring.jpa.hibernate.ddl-auto value should be create, update, create-drop not other then it will give an exception, where the correct meaning for these value -
Create : when the server will start all entity will be newly created
Update : when the server will start container will find which entities are update and which all are newly created the same thing will happen inside database as well old table will update as per the entity and newly table will created
Create-drop: when the server will start then auto all entity will crete and when the server will stop all the entities will auto remove from database
none : it means database ddl will not impact from back-end application Note: Production environment always set with none value

Resources