在Spring Boot中加载初始化数据

在Spring Boot中加载初始化数据java

在Spring Boot中,Spring Boot会自动搜索映射的Entity,而且建立相应的table,可是有时候咱们但愿自定义某些内容,这时候咱们就须要使用到data.sql和schema.sql。git

依赖条件

Spring Boot的依赖咱们就不将了,由于本例将会有数据库的操做,咱们这里使用H2内存数据库方便测试:github

<dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

咱们须要使用JPA来建立Entity:spring

@Entity
public class Country {
 
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;
     
    @Column(nullable = false)
    private String name;
 
    //...
}

咱们这样定义repository:sql

public interface CountryRepository extends CrudRepository<Country, Integer> {
    List<Country> findByName(String name);
}

若是这时候咱们启动Spring Boot程序,将会自动建立Country表。shell

data.sql文件

上面咱们建立好了数据表格,咱们可使用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');

在data.sql文件中咱们插入了4条数据,能够写个测试例子测试一下:springboot

@RunWith(SpringRunner.class)
@SpringBootTest(classes = LoadIniDataApp.class)
public class SpringBootInitialLoadIntegrationTest {

    @Autowired
    private CountryRepository countryRepository;

    @Test
    public void testInitDataForTestClass() {
        assertEquals(4, countryRepository.count());
    }
}

schema.sql 文件

有时候咱们须要自定义数据库的schema,这时候咱们可使用到schema.sql文件。spring-boot

先看一个schema.sql的例子:单元测试

CREATE TABLE country (
    id   INTEGER      NOT NULL AUTO_INCREMENT,
    name VARCHAR(128) NOT NULL,
    PRIMARY KEY (id)
);

Spring Boot会自动加载这个schema文件。

咱们须要关闭spring boot的schema自动建立功能以防冲突:

spring.jpa.hibernate.ddl-auto=none

spring.jpa.hibernate.ddl-auto 有以下几个选项:

  • create : 首先drop现有的tables,而后建立新的tables
  • update : 这个模式不会删除现有的tables,它会比较现有的tables和新的注解或者xml配置是否一致,而后更新。
  • create-drop : 和create很相似,不一样的是会在程序运行完毕后自动drop掉tables。一般用在单元测试中。
  • validate : 只会作table是否存在的验证,不存在则会报错。
  • none : 关闭ddl自动生成功能。

若是Spring Boot没有检测到自定义的schema manager的话,则会自动使用create-drop模式。不然使用none模式。

@sql注解

@Sql 是测试包中的一个注解,能够显示的导入要执行的sql文件,它能够用在class上或者方法之上,以下所示:

@Test
   @Sql({"classpath:new_country.sql"})
   public void testLoadDataForTestCase() {
       assertEquals(6, countryRepository.count());
   }

上面的例子将会显示的导入classpath中的new_country.sql文件。

@Sql有以下几个属性:

  • config : 用来配置SQL脚本,咱们在下面的@SqlConfig详细讲解。
  • executionPhase : 能够选择脚本是在BEFORE_TEST_METHOD 或者 AFTER_TEST_METHOD来执行。
  • statements: 能够接受内联的sql语句
  • scripts: 能够指明要执行脚本的路径

@SqlConfig 注解

@SqlConfig主要用在class级别或者用在@Sql注解的config属性中:

@Sql(scripts = {"classpath:new_country2.sql"},
            config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED))

@SqlConfig有以下几个属性:

  • blockCommentStartDelimiter: 指明了SQL脚本的开始标记。
  • blockCommentEndDelimiter: SQL脚本的结束标记。
  • commentPrefix: SQL 脚本的注释标记
  • dataSource : javax.sql.DataSource的名字,指定该脚本将会在什么datasource下执行
  • encoding: SQL 文件的编码
  • errorMode: 脚本遇到错误的处理模式
  • separator: 分隔符
  • transactionManager: 指定的PlatformTransactionManager
  • transactionMode: 事务模式

@Sql是能够多个同时使用的,以下所示:

@Test
    @Sql({"classpath:new_country.sql"})
    @Sql(scripts = {"classpath:new_country2.sql"},
            config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED))
    public void testLoadDataForTestCase() {
        assertEquals(6, countryRepository.count());
    }

本文的例子能够参考 : https://github.com/ddean2009/learn-springboot2/tree/master/springboot-load-ini-data

更多教程请参考 flydean的博客

相关文章
相关标签/搜索