以下代码正在创建test.mv.db文件。它也可以正常运行并显示它已在数据库中插入数据。
架构:
create table Customer (
id identity,
firstname varchar(20) not null,
lastname varchar(20) not null
);
主类:
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
CustomerRepository repo = ctx.getBean(CustomerRepository.class);
Customer c1 = new Customer("John", "Doe");
Customer c2 = new Customer("Jane", "Doe");
// insert
c1 = repo.save(c1);
c2 = repo.save(c2);
for(Customer t : repo.findAll()) {
System.out.println(t.getFirstName()+", "+t.getLastName());
}
ctx.close();
}
}
配置:
@Configuration
@ComponentScan
public class Config {
@Bean
public DataSource datasource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:~/test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
Resource schema = new ClassPathResource("schema.sql");
ResourceDatabasePopulator dbp = new ResourceDatabasePopulator();
dbp.addScript(schema);
DatabasePopulatorUtils.execute(dbp, ds);
return ds;
}
@Bean
public JdbcOperations jdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);
}
}
客户类:
public class Customer {
private Long id;
private String firstName;
private String lastName;
public Customer() {}
public Customer(Long id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Customer(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
CustomerRepository Interface:
public interface CustomerRepository {
Customer findOne(long id);
Customer save(Customer cust);
List<Customer> findAll();
int update(Customer cust);
int delete (Customer cust);
}
CustomerRepositoryImpl:
@Repository
public class CustomerRepositoryImpl implements CustomerRepository {
@Autowired
private JdbcOperations jdbc;
private static final String SQL_INSERT = "insert into customer (firstname, lastname) values (?, ?)";
private static final String SQL_UPDATE = "update customer set firstname=?, lastname=? where id=?";
private static final String SQL_FIND_ONE = "select * from customer where id = ?";
private static final String SQL_FIND_ALL = "select * from customer order by lastname";
private static final String SQL_DELETE_ONE = "delete from customer where id = ?";
public Customer findOne(long id) {
return jdbc.queryForObject(SQL_FIND_ONE, new CustomerRowMapper(), id);
}
public Customer save(final Customer cust) {
KeyHolder holder = new GeneratedKeyHolder();
int rows = jdbc.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement(SQL_INSERT, new String[]{"id"});
ps.setString(1, cust.getFirstName());
ps.setString(2, cust.getLastName());
return ps;
}
}, holder);
if(rows == 1) { // success, so apply ID to the customer object
cust.setId((Long)holder.getKey());
return cust;
}
return null;
}
public List<Customer> findAll() {
return jdbc.query(SQL_FIND_ALL, new CustomerRowMapper());
}
public int update(Customer cust) {
return jdbc.update(SQL_UPDATE, cust.getFirstName(), cust.getLastName(), cust.getId());
}
public int delete(Customer cust) {
return jdbc.update(SQL_DELETE_ONE, cust.getId());
}
private class CustomerRowMapper implements RowMapper<Customer> {
public Customer mapRow(ResultSet rs, int row) throws SQLException {
return new Customer(rs.getLong("id"), rs.getString("firstname"), rs.getString("lastname"));
}
}
}
堆栈跟踪:
Aug 14, 2017 9:45:42 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@b81eda8: startup date [Mon Aug 14 21:45:42 BDT 2017]; root of context hierarchy
Aug 14, 2017 9:45:43 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.h2.Driver
Aug 14, 2017 9:45:43 PM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executing SQL script from class path resource [schema.sql]
Aug 14, 2017 9:45:43 PM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executed SQL script from class path resource [schema.sql] in 28 ms.
Aug 14, 2017 9:45:43 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@b81eda8: startup date [Mon Aug 14 21:45:42 BDT 2017]; root of context hierarchy
John, Doe
Jane, Doe
问题
但是在第二次运行时,先前保存的数据不再存在。首先我用dbeaver检查,如果数据库中有任何名为Customer的表。我找不到任何。
然后我评论了以下几行 -
c1 = repo.save(c1);
c2 = repo.save(c2);
来自App.java的
但是,如果有任何数据,它将从那里用
读取它for(Customer t : repo.findAll()) {
System.out.println(t.getFirstName()+", "+t.getLastName());
}
但这里也没有运气。
请问有什么问题?
在数据库保存在PC中的情况下,也欢迎使用derby的工作解决方案。