2017-05-17 8 views
0

私はインターネット上の簡単なHibernateチュートリアルに従っています。 executeUpdateが成功したようです(返された行数は1でした)。しかし、私がlist()を呼び出すと、私は古い結果を返しました。これは休止状態の予想される動作ですか?とにかく、同じトランザクションで更新されたデータを取得できますか?結果が返されたHibernate executeUpdateは成功しましたが、リスト操作が変更を反映していません

//Prep work 
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 
    Session session = sessionFactory.getCurrentSession(); 

    //Get All Employees 
    Transaction tx = session.beginTransaction(); 
    Query query = session.createQuery("from Employee"); 
    List<Employee> empList = query.list(); 
    for(Employee emp : empList){ 
     System.out.println("List of Employees::"+emp.getId()+","+emp.getAddress().getCity()); 
    } 
    //Update Employee 
    query = session.createQuery("update Employee set name= :name where id= :id"); 
    query.setParameter("name", "Pankaj Kumar"); 
    query.setLong("id", 1); 
    int result = query.executeUpdate(); 
    System.out.println("Employee Update Status="+result); 


    query = session.createQuery("from Employee"); 
    empList = query.list(); 
    for(Employee emp : empList){ 
     System.out.println("List of Employees::"+emp.getId()+","+emp.getAddress().getCity()); 
    } 

    //rolling back to save the test data 
    tx.rollback(); 

    //closing hibernate resources 
    sessionFactory.close(); 

は、これは私のソースコードである

List of Employees::1,San Jose 
List of Employees::2,Santa Clara 
List of Employees::3,Bangalore 
List of Employees::4,New Delhi 
Hibernate: update EMPLOYEE set emp_name=? where emp_id=? 
Employee Update Status=1 
Hibernate: select employee0_.emp_id as emp_id1_1_, employee0_.emp_name as emp_name2_1_, employee0_.emp_salary as emp_sala3_1_ from EMPLOYEE employee0_ 
List of Employees::1,San Jose 
List of Employees::2,Santa Clara 
List of Employees::3,Bangalore 
List of Employees::4,New Delhi 

答えて

0

あなたは再び同じクエリを実行されますが、最初transacation、あなたが作ったので、変更をコミットしたことがありません永続化されませんでした。これを解決するには、あなたが休止状態のトランザクションをコミットしてみてくださいすることができます

tx.commit(); 

パターンを使用すると、このように見える何かを使用する必要があります。これはtry-catchブロックで行わなければならないこと

Transaction tx = session.beginTransaction(); 
Query query = session.createQuery("from Employee"); 
List<Employee> empList = query.list(); 
// update, insert, etc. 
tx.commit(); 

注意を、例外が発生すると、トランザクション全体をロールバックすることができます。

+0

更新が正常に完了した場合でもトランザクションをロールバックするにはどうすればよいですか? – XtremeBaumer

+0

@Tim Biegeleisenなぜあなたは 'tx.commit();'を選択した後、私はそれが更新後になるはずだと思いましたか? –

+0

@XtremeBaumer OPを読んだとき、私はこの要件が表示されません。あなたのコメントを精緻化できますか? –

0

変更は、トランザクションがコミットされた後、つまりトランザクションの全体のポイントに実際にDBに保存されます。

データベースのデータを更新する必要があるシナリオに直面した場合は、さらに処理するために取得して、永続コンテキストに存在するオブジェクト上でローカルに更新するか(この場合、クエリの代わりにcreateOrUpdateを実行するか、2つのトランザクションで2つの手順を分ける

0

updateをDBに、rollbackを更新が成功したことをテストしたいと思っています。その場合は、トランザクション内でsavePointを持っている必要があります。この投稿Creating savepoint and rollingback in hibernateが役に立ちます。

関連する問題