在Spring Boot中加载初始化数据
在Spring Boot中,Spring Boot会自动搜索映射的实体,并创建相应的表,但是有时候我们希望自定义某些内容,这时候我们就需要使用到data.sql和schema.sql。
Spring Boot的依赖我们就不将了,因为本例将会有数据库的操作,我们这里使用H2内存数据库方便测试:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> 复制代码
我们需要使用JPA来创建实体:
@Entity public class Country { @Id @GeneratedValue(strategy = IDENTITY) private Integer id; @Column(nullable = false) private String name; //... } 复制代码
我们这样定义的存储库:
public interface CountryRepository extends CrudRepository<Country, Integer> { List<Country> findByName(String name);
} 复制代码
如果这时候我们启动Spring Boot程序,将会自动创建Country表。
上面我们创建好了数据表格,我们可以使用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条数据,可以写一个测试示例测试一下:
@RunWith(SpringRunner.class) @SpringBootTest(classes = LoadIniDataApp.class) public class SpringBootInitialLoadIntegrationTest { @Autowired private CountryRepository countryRepository; @Test public void testInitDataForTestClass() {
assertEquals(4, countryRepository.count());
}
} 复制代码
有时候我们需要自定义数据库的schema,这时候我们可以使用到schema.sql文件。
先看一个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有如下几个选项:
如果Spring Boot没有检测到自定义的模式管理器的话,可以自动使用create-drop模式。否则使用none模式。
@Sql是测试包中的一个注解,可以显示的引入要执行的sql文件,它可以用在类上或者方法之上,如下所示:
@Test @Sql({"classpath:new_country.sql"}) public void testLoadDataForTestCase() {
assertEquals(6, countryRepository.count());
} 复制代码
上面的例子将会显示的引入classpath中的new_country.sql文件。
@Sql有如下几个属性:
@SqlConfig主要用在类级别或用在@Sql注解的配置属性中:
@Sql(scripts = {"classpath:new_country2.sql"},
config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED)) 复制代码
@SqlConfig有如下几个属性:
@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());
}