有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java hibernate不会在应用程序结束后将数据保存到本地h2数据库

我有一个从h2数据库保存和读取数据的类。如果我使用“mem”属性,它可以正常工作。但如果我使用“file”属性,在我停止程序后,所有数据都会从数据库中删除。 我的hibernate cfg:

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:file:d:\WebProjectDb</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">false</property>

        <property name="hbm2ddl.auto">update</property>

        <mapping class="com.webproject.Courses"/>



    </session-factory>
</hibernate-configuration>

这是我从db读取和保存的方法: SessionFactory sf=新的AnnotationConfiguration()。配置()。buildSessionFactory()

public void save(Courses user) {

Session session = sf.openSession();
session.save(user);
session.flush();
session.close();
}

public List<Courses> getCourses(){

Session session = sf.openSession();
List courses = session.createQuery("from Courses").list();
session.close();
return courses;
}

我非常感激任何帮助


共 (1) 个答案

  1. # 1 楼答案

    save()方法需要transaction,所以需要添加它,如下代码所示,并附上注释:

    public void save(Courses user) {
         try {
           Session session = sf.openSession();
           Transaction transaction = session.beginTransaction();//start transaction
           session.save(user);
           session.flush();
           transaction.commit();//commit the transaction
        } catch(Exception exe) {
          ex.printStackTrace();  
          tx.rollback();  //rollback the transaction upon exception
        } finally {
           session.close();//close the session in finally always
        }
    }