Java 如何以及为什么在H2 Spring数据库中使用脚本
我打算制作一个符合以下要求的程序:Java 如何以及为什么在H2 Spring数据库中使用脚本,java,spring,h2,Java,Spring,H2,我打算制作一个符合以下要求的程序: 在应用程序开始时,程序检查是否存在 已经创建了一个数据库 如果不是:创建一个 如果是:使用它 数据库存储和更新数据(Customers.java) 运行时 一旦应用程序关闭,数据库就会被关闭 应该为下一次执行保存数据 到目前为止,这项计划还没有完成 目前,我有基本的代码来测试我的实现中的功能性 @EnableTransactionManagement @EnableAutoConfiguration @ComponentScan() @SpringBootAp
@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()));
};
}
}
script.sql
CREATE TABLE Customers (
id IDENTITY,
section VARCHAR(20) NOT NULL,
);
- 我不明白这种实施的利弊李>
- 为什么要使用script.sql这样的脚本来创建表
有人能给我解释一下吗?使用JdbcTemplate时,数据库中的数据库和表将不可用,我们导入script.sql以创建表的 如果您通过设置hibernate属性来使用hibernatehibernate.hbm2ddl.autocreate/update/etc 这将满足你的第五个问题
(5.一旦应用程序关闭,数据库应继续存储下一次执行所需的数据)但我在应用程序中使用了带有“CREATE TABLE”的JdbcTemplate,它正在工作。所以它似乎是可用的?但是您写了“JDBCTemplateDB和Table在数据库中不可用”,我的意思是我不使用hibernate,我看到的教程也不使用。对不起,你能用另一种方式解释一下你的意思吗?谢谢:)将项目部署到其他服务器时,数据库中没有该脚本的可用表。sql文件将帮助您创建表,无需在数据库中手动创建表
CREATE TABLE Customers (
id IDENTITY,
section VARCHAR(20) NOT NULL,
);