休眠并不'在应用程序结束后将数据保存到本地h2数据库

问题描述:

我有一个保存并从h2数据库读取数据的类。如果我使用“mem”属性,它工作正常。但是,如果我使用“文件”属性,我停止程序后,所有数据从数据库中删除。 。 我休眠CFG:休眠并不'在应用程序结束后将数据保存到本地h2数据库

<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; 
} 

我会apreciate任何帮助。

+0

我没有看到你的代码中的事务。在你的保存方法中,最后尝试'tx = session.beginTransaction()',然后'tx.commit()'。 – Lucian

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 
    } 
}