2016-12-04 11 views
1

私はh2データベースからデータを保存して読み込むクラスを持っています。私は "mem"プロパティを使用する場合、それは正常に動作します。しかし、私が "ファイル"プロパティを使用する場合、私はプログラムを停止した後、すべてのデータがdbから削除されます。 。 マイ休止CFG:hibernate doesnt 'アプリケーションの終了後にローカルの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; 
} 

私は何か助けになるでしょう。

+0

私はあなたのコード内での取引が表示されません。 saveメソッドでは、 'tx = session.beginTransaction()'と最後に 'tx.commit()'を試してみてください。 – Lucian

答えて

0

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 
    } 
} 
関連する問題