在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来加载文件:数据库
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,这时候咱们可使用到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 有以下几个选项:
若是Spring Boot没有检测到自定义的schema manager的话,则会自动使用create-drop模式。不然使用none模式。
@Sql 是测试包中的一个注解,能够显示的导入要执行的sql文件,它能够用在class上或者方法之上,以下所示:
@Test @Sql({"classpath:new_country.sql"}) public void testLoadDataForTestCase() { assertEquals(6, countryRepository.count()); }
上面的例子将会显示的导入classpath中的new_country.sql文件。
@Sql有以下几个属性:
@SqlConfig主要用在class级别或者用在@Sql注解的config属性中:
@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()); }
本文的例子能够参考 : https://github.com/ddean2009/learn-springboot2/tree/master/springboot-load-ini-data
更多教程请参考 flydean的博客