2

Is there any way in spring boot for hibernate to add some data.sql only after particular entity-table is created. (I don't want initialization of schema & data while initializing spring boot application)

    package io.fall.model;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name = "userprofile")
    public class UserProfile {
        
        @Id
        @GeneratedValue
        private int id;
        private int theme;
        private String userName;

        UserProfile(){}

        public int getTheme() {
            return theme;
        }

        public void setTheme(int theme) {
            this.theme = theme;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }
    }

I want to insert these values after hibernate creates entity-table userprofile

INSERT INTO userprofile (id,theme,userName,summary) 
VALUES (1, 1 , 'John Doee'),
       (2, 2 , 'Jenny Doee'),
       (3, 3 , 'James Doee');
SternK
  • 11,649
  • 22
  • 32
  • 46
Shiru99
  • 429
  • 7
  • 12
  • 1
    Hibernate doesn't have such functionality. But you can achieve that using spring or even you can use flyway or liquibase for such things. – Lucia Jul 20 '21 at 04:57

2 Answers2

1

It sounds like you are looking at the wrong tool. Take a look at Liquibase or Flyway which you probably want to use once you are moving off developer stage toward production.

But since you are asking about Spring Boot and Hibernate: You can achieve it with Spring Boot.

  1. Make sure userprofile.id has a unique constraint
  2. Create a data.sql wich contains the insert statement.
  3. In your application.properties set spring.datasource.continue-on-error=true

The insert statement will get executed on every startup, but will fail after the first time. Spring Boot will just ignore this error, since you told it so with the application properties.

This assumes the inserted values stay in the database and don't get deleted.

The drawback of this approach is that ignoring errors might result in you missing other problems with the inserts or other SQL statements.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
1

If you use hibernate schema generation then you can try to use importing script files for your purpose.

spring.jpa.properties.hibernate.hbm2ddl.import_files=data.sql

Hibernate will execute the script file after the schema is automatically generated.

Or you can use also javax.persistence.schema-generation.create-script-source property (see this section of the documentation) for the same purpose.

SternK
  • 11,649
  • 22
  • 32
  • 46