2017-02-14 59 views
0

在我目前的Spring項目,我有我的rootCOntext.xml文件這個Hibernate配置:休眠,不會持續在數據庫上的數據(參見更新3)

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:p="http://www.springframework.org/schema/p" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:security="http://www.springframework.org/schema/security" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
     <property name="driverClassName" value="org.postgresql.Driver"/> 
     <property name="url" value="jdbc:postgresql:mydata"/> 
     <property name="username" value="klebermo"/> 
     <property name="password" value="123"/> 
    </bean> 

    <bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource"/> 
     <property name="packagesToScan" value="org.kleber.model" /> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> 
       <prop key="hibernate.show_sql">false</prop> 
       <prop key="hibernate.hbm2ddl.auto">create-drop</prop> 
      </props> 
     </property> 
    </bean> 

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/> 
    </bean> 

    <tx:annotation-driven transaction-manager="transactionManager"/> 
</beans> 

但是當應用程序需要執行這個查詢:

@Transactional 
public List<E> select(String orderby, String groupby) { 
    return (List<E>) this.getCurrentSession().createCriteria(clazz).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); 
} 

被包含在這個類:

public abstract class Dao<E> { 
    protected Class<E> clazz; 

    @Autowired 
    protected SessionFactory sessionFactory; 

    public Dao(Class<E> clazz) { 
     this.clazz = clazz; 
    } 

    public Session getCurrentSession() { 
     return sessionFactory.getCurrentSession(); 
    } 
    ... 
} 

我得到這個錯誤:

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread 
    org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134) 
    org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:456) 
    org.kleber.model.Dao.getCurrentSession(Dao.java:22) 
    org.kleber.model.Dao.select(Dao.java:43) 
    org.kleber.model.Service.select(Service.java:35) 
    org.kleber.model.Controller.list(Controller.java:87) 
    org.kleber.model.Controller$$FastClassBySpringCGLIB$$aa38cb3a.invoke(<generated>) 
    org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) 
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:652) 
    org.kleber.model.usuario.UsuarioController$$EnhancerBySpringCGLIB$$7dce8c33.list(<generated>) 
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    java.lang.reflect.Method.invoke(Method.java:498) 
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) 
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) 
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) 
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) 
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) 
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) 
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) 
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) 
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622) 
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729) 
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) 
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) 
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:158) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) 
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) 
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) 
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) 
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) 
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) 
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) 

任何人都可以看到這裏有什麼問題?

UPDATE

我改變我的DAO方法是:

@Transactional 
public List<E> select(String orderby, String groupby) { 
    Session sess = sessionFactory.openSession(); 
    Transaction tx = null; 
    List<E> list = null; 
    try { 
     tx = sess.beginTransaction(); 
     list = sess.createCriteria(clazz).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); 
     tx.commit(); 
    } catch (Exception e) { 
     if(tx != null) 
      tx.rollback(); 
     throw e; 
    } finally { 
     sess.close(); 
    } 
    return list; 
    //return (List<E>) this.getCurrentSession().createCriteria(clazz).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); 
} 

,現在我收到此錯誤:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.kleber.model.usuario.Usuario.listas, could not initialize proxy - no Session 
    org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:582) 
    org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201) 
    org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:145) 
    org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:261) 
    com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:102) 
    com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25) 
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) 
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) 
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) 
    com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:119) 
    com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:79) 
    com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:18) 
    com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292) 
    com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681) 
    com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057) 
    org.kleber.model.Controller.list(Controller.java:88) 
    org.kleber.model.Controller$$FastClassBySpringCGLIB$$aa38cb3a.invoke(<generated>) 
    org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) 
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:652) 
    org.kleber.model.usuario.UsuarioController$$EnhancerBySpringCGLIB$$7c57ca50.list(<generated>) 
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    java.lang.reflect.Method.invoke(Method.java:498) 
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) 
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) 
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) 
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) 
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) 
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) 
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) 
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) 
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622) 
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729) 
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) 
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) 
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:158) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) 
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) 
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) 
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) 
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) 
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) 
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) 

我猜點的如何問題我從模型層實現我的課堂之間的關係。

這是我的課:

public class Usuario { 
@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY) 
private Integer id; 

@Column 
@Input 
@Text 
private String login; 

@Column 
@Input 
@Password 
private String senha; 

@Column 
@Input 
@Text 
private String nome; 

@Column 
@Input 
@Text 
private String sobrenome; 

@Column 
@Input 
@Email 
private String email; 

@OneToOne 
private Cart cesta; 

@ManyToMany 
private List<Wishlist> listas; 

@ManyToMany 
private List<Orders> pedidos; 

@ManyToMany 
@Select 
private List<Credencial> credenciais; 

@Column 
@Input 
@Date 
private java.util.Date expirationDate; 

@Column 
@Input 
@Checkbox 
private Boolean locked; 

@Column 
@Input 
@Checkbox 
private Boolean enabled; 
} 

有人知道如何解決這個問題?沒有使用FetchType.EAGER作爲ManyToMany關係(如果我那樣做,應用程序甚至不會啓動,因爲我得到一個錯誤hibernate無法獲取多個包)。

更新2

我嘗試這在我的DAO方法:

@Transactional 
public List<E> select(String orderby, String groupby) { 
    Session sess = sessionFactory.openSession(); 
    Transaction tx = null; 
    List<E> list = null; 
    try { 
     tx = sess.beginTransaction(); 

     Criteria criteria = this.getCurrentSession().createCriteria(clazz); 
     if(orderby != null) 
      criteria = criteria.addOrder(Order.asc(orderby)); 
     if(groupby != null) 
      //TODO 
     for(Field field : clazz.getDeclaredFields()) { 
      if(field.isAnnotationPresent(ManyToMany.class)) 
       criteria = criteria.setFetchMode(field.getName(), FetchMode.EAGER); 
     } 
     list = criteria.list(); 

     tx.commit(); 
    } catch (Exception e) { 
     if(tx != null) 
      tx.rollback(); 
     throw e; 
    } finally { 
     sess.close(); 
    } 
    return list; 
} 

,現在我得到一個在這篇文章中提到的第一個錯誤。

更新3

所以,我設法解決這個錯誤改變方法getCurrentSession() DAO類到:

public Session getCurrentSession() { 
    return sessionFactory.openSession(); 
} 

但現在當我從我的形式提交的數據,他們不持久在數據庫上,儘管沒有錯誤被觸發。

+0

你好。我想幫助你解決這個問題。是否需要使用基於xml的配置? – Taras

+0

是的,這是我目前正在使用的項目。 –

+0

還需要使用Criteria API。我的意思是可以使用HQL嗎? – Taras

回答

0

有你的代碼的多個問題。讓我們從頭開始。

@Transactional不適用於您的情況。這從您複製的堆棧跟蹤中清晰可見,因爲Spring使用代理對象來實現事務性調用。正如我所看到的,你的配置應該沒問題,所以我唯一能想到的就是你使用了錯誤的註釋。

不幸的是有2個@Transactional註解,一個來自javax.transaction包,另一個來自org.springframework.transaction.annotation包。顯然,你必須使用後者,否則將無法正常工作。

第二件事,懶惰的初始化異常。發生這種情況是因爲您試圖初始化事務外的懶惰關係。

有多種方案來解決這個:

  1. 把它拿來交易
  2. 內直接與原始查詢

的第一件事會解決這個問題取它,但是它不會與第二種解決方案相比,表現非常出色。

的第一件事,你可以通過調用延遲集合的任何方法做到這一點,例如

list.getLazyCollection().size() 

,或者你可以使用Hibernate的機制來做到這一點:

Hibernate.initialize(list.getLazyCollection()) 

唯一重要的是在交易中做到這一點。

後一種直接獲取關係的解決方案涉及到JPQL/HQL查詢或Criteria API。

0

我用同樣的包,你和我在我的xml配置文件中的兩個附加條目:

<context:component-scan base-package="com.mypkg.daos"/> 
<context:annotation-config/> 

當您使用@Transactional@Autowried註解的話,我想這將是添加一個好主意這兩個配置屬性。

+0

但是我有兩個條目,在我的'applicationContext.xml'文件中,我的'web.xml'中引用了'init-param'標記,它與'org.springframework.web.servlet.DispatcherServlet'的servlet條目相關聯。我是否也需要在我的'rootContext.xml'文件中複製它們? –

+0

是的,我有他們複製,所以你可以給它一個 –

+0

好吧,我這樣做,但不解決問題(發生相同的錯誤)。 –

0

我想這春風不能夠正確地注射SessionFactory

我將使春天註釋交易在你的XML;試着在這裏看看http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html;你應該在你的配置類此@EnableTransactionManagement添加或通過在XML中添加啓用事務或本:<tx:annotation-driven/>

那我會做如下:

我會寫這個倉庫DAO

@Repository 
    public class Dao<E> { 
     protected Class<E> clazz; 

     @Autowired 
     protected SessionFactory sessionFactory; 

     public Dao(Class<E> clazz) { 
      this.clazz = clazz; 
     } 

     public Session getCurrentSession() { 
      return sessionFactory.getCurrentSession(); 
     } 
     public List<E> select(String orderby, String groupby) 
     { 
     return (List<E>) this.getCurrentSession().createCriteria(clazz).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); 
     } 
    } 

然後我想創建一個服務類,我會做以下

@Service 
public class ServiceClass<E> 
{ 
    @Autowired 
    private Dao<E> repos; 

@Transactional 
public List<E> select(String orderby, String groupby) { 
    return repos.select(orderby, groupby); 
} 
} 

我希望這是有用

安傑洛

+0

通過我的XML配置中的'我的項目已經啓用了事務處理,並且我有'@ Transactional'註釋我的Dao和Service類。仍然不工作。 –

+0

@KleberMota不會將事務放在DAO上,但只能在服務中使用 –

0

我建議嘗試設置數據源上的transactionManager的,而不是SessionFactory的,像這樣:

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <property name="dataSource" ref="dataSource"/> 
</bean> 

之所以有這樣的變化可以在此link找到。 此外,確保您具備以下條件:宣佈你的xml文件

  1. <tx:annotation-driven transaction-manager="transactionManager"/>,你的情況在rootContext.xml.
  2. <context:component-scan base-package="com.myproject"/>使豆可見的春天。
  3. @Repository你的DAO。
  4. @Transactional您的方法或課程級別。

    1. 和4.讓Spring應用並創建具有Transaction支持的代理。
+0

transactionManager不能只使用'dataSource'屬性(應用程序甚至不啓動)。如果我嘗試使用'dataSource'和'sessionFactory',則會發生相同的錯誤。關於其他選項,所有這些選項都已經就位。 –