2016-09-18 109 views
1

我下面就Hibernate的教程,看到下面的代碼:休眠堅持不交易

package com.websystique.spring.dao; 

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 

public abstract class AbstractDao { 

    @Autowired 
    private SessionFactory sessionFactory; 

    protected Session getSession() { 
     return sessionFactory.getCurrentSession(); 
    } 

    public void persist(Object entity) { 
     getSession().persist(entity); 
    } 

    public void delete(Object entity) { 
     getSession().delete(entity); 
    } 
} 

我在想,如果persist()(或save()delete())而不事務中使用?在這裏似乎是這種情況。

+0

我會通過,這是爲各種各樣的原因非常差代碼注意。理想情況下,使用Spring Data JPA(並使用構造函數注入)。 – chrylis

+0

感謝,將調查那些 – Liumx31

回答

1

你不能保存或堅持對象沒有事務你必須在保存對象後提交事務否則它不會保存在數據庫中。 沒有交易,你只能從數據庫

+0

所以教程代碼不起作用? – Liumx31

1

至於說你不能保存在數據庫中的任何事情沒有活動的事務檢索對象。 它注意到你正在使用一個容器,在這個例子中是Spring。 Spring可以通過像JavaEE這樣的interceptos來控制事務。 你可以在這裏閱讀更多:http://docs.jboss.org/weld/reference/2.4.0.Final/en-US/html/interceptors.html

而且這看起來像一個真正的窮人例子來說明:

public class TransactionalInterceptor { 

    @Inject 
    private Session session; 

    @AroundInvoke 
    public Object logMethodEntry(InvocationContext ctx) throws Exception { 
     Object result = null; 
     boolean openTransaction = !session.getTransaction().isActive(); 
     if(openTransaction) 
      session.getTransaction().begin(); 
     try { 
      result = ctx.proceed(); 
      if(openTransaction) 
       session.getTransaction().commit(); 
     } catch (Exception e) { 
      session.getTransaction().rollback(); 
      throw new TransactionException(e); 
     } 
     return result; 
    } 

}