如何以及为什么使用与H2春数据库脚本
问题描述:
我打算把这些要求运行的程序:如何以及为什么使用与H2春数据库脚本
- 在应用程序的启动程序会检查是否有 已经是一个数据库中创建
- 如果不是:创建一个
- 如果是:使用它
- 数据库在 运行时期存储和更新数据(Customers.java)。
- 一旦应用程序关闭,数据库 应该继续存储下次执行的数据。
到目前为止的计划。
目前,我有一个基本的代码来测试后的功能我在执行
@EnableTransactionManagement
@EnableAutoConfiguration
@ComponentScan()
@SpringBootApplication
public class DemoApplication {
private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
@Autowired
private ApplicationContext context;
@Autowired
QueryRepoImp queryRepoImp;
@Autowired
JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
/*
CreateH2Database createH2Database = new CreateH2Database();
createH2Database.create();
*/
}
@Bean
public CommandLineRunner clr() {
return a -> {
log.info("Creating tables");
// jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS customers(" +
"id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");
// Split up the array of whole names into an array of first/last names
List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
.map(name -> name.split(" "))
.collect(Collectors.toList());
// Use a Java 8 stream to print out each tuple of the list
splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));
// Uses JdbcTemplate's batchUpdate operation to bulk load data
jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);
log.info("Querying for customer records where first_name = 'Josh':");
jdbcTemplate.query(
"SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[]{"Josh"},
(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
).forEach(customer -> log.info(customer.toString()));
};
}
}
我看到一些教程里的人创建了一个数据库,这样的脚本(不同的实施):
@Configuration
@ComponentScan
public class SpringRootConfig {
@Bean(name = "scriptedDataSource")
public DataSource datasource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript("script.sql").build();
}
@Bean
public JdbcOperations jdbcTemplate(@Qualifier("scriptedDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
script.sql
CREATE TABLE Customers (
id IDENTITY,
section VARCHAR(20) NOT NULL,
);
- 我不理解,实现的PRO /缺点是什么?
- 为什么我应该使用脚本如script.sql来创建表?
有人可以解释一下给我吗?
答
在使用的JdbcTemplate DB和表不会在数据库中供我们导入了创建表的
在情况下,如果你正在使用Hibernate script.sql通过设置休眠特性hibernate.hbm2ddl.auto创建/更新/等
它会满足你的第五届问题
(5.一旦应用程序被关闭数据库应保持存储数据下一个执行)
但我在我的应用程序中使用JdbcTemplate和“CREATE TABLE”,它正在工作。所以它似乎可用? – AnnaKlein
是的!其可用.... –
但你写了“JdbcTemplate Db和表将不会在数据库中可用”我的意思是我不使用休眠和我看到的教程也没有。对不起,你能以不同的方式解释你的意思吗?谢谢:) – AnnaKlein