下面给了我:
org.h2.jdbc.JdbcSQLException:表“FOO”已经存在;SQL语句
这让我感到困惑,并希望得到一些澄清。
H2 服务器何时启动/关闭,由getConnection和close?
为什么会already exists发生?当 H2 服务器启动时,模式是否从以前的会话中持久化?
在 H2 中设置测试模式和数据集以用于数据库单元测试的任何最佳实践建议?
public class MyTest {
@Before
public void setUp() throws ClassNotFoundException, SQLException {
try {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/test;MODE=Oracle", "sa", "");
// add application code here
Statement statement =conn.createStatement();
statement.execute("create table foo (id integer)");
conn.commit();
ResultSet rs = statement.executeQuery("select * from foo");
if (rs.next()) {
System.out.println(rs.getString("id"));
}
statement.execute("insert into foo (id) values (5)");
conn.commit();
rs = statement.executeQuery("select * from foo");
if (rs.next()) {
System.out.println(rs.getString("id"));
}
conn.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
@Test
public void test() {
}
}
Run Code Online (Sandbox Code Playgroud)
问题在这里:
DriverManager.getConnection("jdbc:h2:~/test;MODE=Oracle", "sa", "");
Run Code Online (Sandbox Code Playgroud)
您的连接字符串告诉 H2 在 下使用文件系统作为存储$HOME/test,因此它在测试中持续存在也就不足为奇了。
从文档:
嵌入:
- jdbc:h2:~/test: 'test' 在用户主目录中
- jdbc:h2:/data/test: 'test' 在目录中/data
内存中:
-jdbc:h2:mem:test一个进程中的多个连接
-jdbc:h2:mem:未命名的私有;一个连接
还有一个服务器模式,但你没有使用它,无论如何它对单元测试没有多大意义。对于单元测试,根据您的测试设计,您可能需要两种内存模式之一。