我正在运行一个Spring MVC项目,并希望有一个表单按钮,将所有数据重置为新的Tomcat启动。我们使用Hibernate和import.sql
脚本在dev环境中启动时填充一些虚拟数据。我正在寻找一种解决方案,实例只需点击一个按钮即可返回此状态(基本上是create
的Hibernate ddl-auto加上import.sql
的导入。这当然不会在生产中运行。
我也愿意将import.sql的内容翻译成程序化(基于Java配置)的解决方案,如果这样做更容易。
这个问题可能已经有了答案,但我还没有找到答案。如果它重复,将关闭它。
答案 0 :(得分:1)
此SO question与您需要做的非常相似。
点击按钮,你需要做的就是这样。
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/?user=user&password=pass");
Statement statement = (Statement) conn.createStatement();
statement.executeUpdate("DROP DATABASE tcs;");
statement.executeUpdate("CREATE DATABASE tcs charset=utf8 collate=utf8_persian_ci;");
然后你需要调用hibernate提供的buildSessionFactory方法来重新创建表。
我希望它有所帮助。
答案 1 :(得分:0)
为什么不使用相同的jdbcurl创建一个使用“create-drop”配置的新SessionFactory,然后在完成后,加载并执行import.sql脚本的内容?
@Test
public void test() {
HsqlSessionFactoryCreator creator = HsqlSessionFactoryCreator.getInstance();
try (SessionFactory sessionFactory1 = creator.create()) {
try (Session session = sessionFactory1.openSession()) {
Transaction transaction = session.beginTransaction();
try {
createEntity(...);
transaction.commit();
} catch (Throwable throwable) {
transaction.rollback();
}
}
try (Session session = sessionFactory1.openSession()) {
System.err.println("SessionFactory1 " + session.createCriteria(MyEntity.class).list());
}
try (Session session = sessionFactory1.openSession()) {
Transaction transaction = session.beginTransaction();
try {
createEntity(...);
transaction.commit();
} catch (Throwable throwable) {
transaction.rollback();
}
}
try (Session session = sessionFactory1.openSession()) {
System.err.println("SessionFactory1 " + session.createCriteria(MyEntity.class).list());
}
try (SessionFactory sessionFactory2 = creator.create()) {
try (Session session = sessionFactory1.openSession()) {
System.err.println("SessionFactory1 after creating SessionFactory2 " + session.createCriteria(MyEntity.class).list());
}
try (Session session = sessionFactory2.openSession()) {
System.err.println("SessionFactory2 " + session.createCriteria(MyEntity.class).list());
}
try (Session session = sessionFactory1.openSession()) {
Transaction transaction = session.beginTransaction();
try {
createEntity(...);
transaction.commit();
} catch (Throwable throwable) {
transaction.rollback();
}
}
try (Session session = sessionFactory1.openSession()) {
System.err.println("SessionFactory1 " + session.createCriteria(MyEntity.class).list());
}
try (Session session = sessionFactory2.openSession()) {
System.err.println("SessionFactory2 " + session.createCriteria(MyEntity.class).list());
}
}
}
}
当我运行测试时(创建了一个具有实体知识的SessionFactory),我得到以下输出
SessionFactory1 [MyEntity[ID 9c81b1fa-04f5-4572-a945-e16d13ffc187]]
SessionFactory1 [MyEntity[ID 550e7c5d-6c8c-40ea-8f4b-cfdbf2d92075], MyEntity[ID 9c81b1fa-04f5-4572-a945-e16d13ffc187]]
SessionFactory1 after creating SessionFactory2 []
SessionFactory2 []
SessionFactory1 [MyEntity[ID 3748127d-6872-4d9c-84fb-1d83b85c9fe0]]
SessionFactory2 [MyEntity[ID 3748127d-6872-4d9c-84fb-1d83b85c9fe0]]