Home > AI > Backend > SpringBoot > mysql-connector-java >

initialize Mysql data

Add Mysql

Add dependency

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

set mysql database

##################
# Mysql
##################
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/test
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true

Add codes

Country.java

@Entity
public class Country {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;

    @Column(nullable = false)
    private String name;

}

CountryRepository.java

public interface CountryRepository extends JpaRepository<Country, String> {
}

Then it will create a table named country under the database you nominated

If you want to initialized the data, you can add data.sql under resources

resources / data.sql

INSERT INTO country (name) VALUES ('India');
INSERT INTO country (name) VALUES ('Brazil');
INSERT INTO country (name) VALUES ('USA');
INSERT INTO country (name) VALUES ('Italy');

add this to application.properties

spring.sql.init.mode=alway

The name of data.sql is predefined by Spring

Run the application again, you will initialized data, but it will be executed whenever you run the application.

Test with @Sql

SqlTest.java

@SpringBootTest
public class SqlTest {

    @Autowired
    private CountryRepository countryRepository;

    @Test
    @Sql({"/data.sql"})
    public void testLoadDataForTestClass() {
        assertEquals(8, countryRepository.findAll().size());
    }
}

It will execute the data.sql, so you should check the double number of the records in the data.sql

Leave a Reply