Initializing the database with Spring JDBC

If the application does not use JPA, or you don't want to depend on the Hibernate functionality explicitly, Spring offers you another way of getting the database set up, as long as the spring-boot-starter-jdbc dependency is present. So let's take a look at what we did to get it to work, as shown in the following list:

  • The spring.jpa.hibernate.ddl-auto=none setting tells Hibernate not to do any automatic handling of the database if the Hibernate dependency also exists, as it does in our case. This setting is good practice for a production environment as you probably don't want to get all of your database tables wiped clean inadvertently. That would be one hell of a disaster, that's for sure!
  • The schema.sql file is expected to exist in the root of the classpath. It is executed by Spring during the schema creation of the database upon every startup of the application. However, unlike Hibernate, this will not drop any of the existing tables automatically, so it might be a good idea to either use DROP TABLE IF EXISTS to delete an existing table before creating the new one, or use CREATE TABLE IF NOT EXISTS as part of the table creation SQL if you only want to create new tables when they don't already exist. This makes it a lot more flexible to declare the database structure evolution logic, thus making it safer to be used in production as well.
  • The data.sql file is expected to exist in the root of the classpath. This is used to execute the data population SQL, so this is where all the INSERT INTO statements go.

Given that this is a Spring native functionality, we will also get the ability to define the schema and data files not only globally, but also as per the specific database platform. For example, we can have one set of files that we can use for Oracle, schema-oracle.sql, and a different one for MySQL, schema-mysql.sql. The same applies to the data.sql variants as well; however, they don't have to be defined per platform, so while you might have platform-specific schema files, there could be a shared data file. The spring.datasource.platform configuration value can be explicitly set if you want to override Spring Boot's automatically deduced value.

In case one wants to override the default names of schema.sql and data.sql, Spring Boot provides the configuration properties, which we can use to control spring.datasource.schema and spring.datasource.data.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.186.218