2015-05-21 5 views
1

Я пытаюсь настроить Spring 4 + Hibernate 4. Я столкнулся с ошибкой: org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread Не могли бы вы помочь определить, где я ошибаюсь? Ниже приведены конфигурации.Spring 4+ Hibernate 4: Не удалось получить синхронизацию с транзакцией для текущего потока

весенне-database.xml:

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 

    <!-- MySQL data source --> 
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost:3306/personal" /> 
     <property name="username" value="root" /> 
     <property name="password" value="password" /> 
    </bean> 

    <!-- Hibernate session factory --> 
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="mappingResources"> 
      <list> 
       <value>/orm/Song.hbm.xml</value> 
      </list> 
     </property> 
     <property name="hibernateProperties"> 
      <props> 
      <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> 
      </props> 
     </property> 
    </bean> 

    <bean id="songDao" class="com.letsdo.impl.SongImpl"> 
     <property name="sessionFactory" ref="sessionFactory"></property> 
    </bean> 

    <!-- MUST have transaction manager, using aop and aspects --> 
    <tx:annotation-driven transaction-manager="transactionManager"/> 
    <bean id="transactionManager" 
     class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory"></property> 
    </bean> 
</beans> 

SongImpl.java:

package com.letsdo.impl; 
import java.util.ArrayList; 
import java.util.List; 

import org.hibernate.Query; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 

import com.letsdo.dao.SongDao; 

@Repository 
@Transactional 
public class SongImpl implements SongDao{ 

    @Autowired 
    private SessionFactory sessionFactory; 

    @SuppressWarnings("unchecked") 
    public List<String> getAllAlbums(){ 
     List<String> allAlbums = new ArrayList<String>(); 
     Query query = getSessionFactory().getCurrentSession().createQuery("Select DISTINCT Album from song"); 
     allAlbums = query.list(); 
     return allAlbums; 

    } 
    public SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

    public void setSessionFactory(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
    } 
} 

HomeController.java:

package com.letsdo.controller; 

import java.util.List; 

import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.security.core.context.SecurityContextHolder; 
import org.springframework.security.core.userdetails.User; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.servlet.ModelAndView; 

import com.letsdo.dao.SongDao; 
import com.letsdo.impl.SongImpl; 

@Controller 
public class HomeController { 

    @Autowired 
    private SongImpl songDao; 
    @RequestMapping(value="/", method=RequestMethod.GET) 
    public ModelAndView welcomePageBeforeLogin(HttpServletRequest request, HttpServletResponse response,HttpSession session){ 
     ModelAndView model = new ModelAndView(); 
     List<String> album = songDao.getAllAlbums(); 
     model.addObject("albumsize",album.size()); 
     model.setViewName("hello"); 
     return model; 
    } 
} 

MVC-диспетчерская-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans  
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-4.0.xsd 
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 

    <context:component-scan base-package="com.letsdo.*" /> 

    <bean 
     class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <property name="prefix"> 
      <value>/WEB-INF/pages/</value> 
     </property> 
     <property name="suffix"> 
      <value>.jsp</value> 
     </property> 
    </bean> 

</beans> 
+2

У вас есть несколько экземпляров вашего dao, 1 транзакций (загруженных 'ContextLoaderListener' и 1 non-transactional (загруженных' DispatcherServlet'). Из-за вашего '' вы эффективно дублируете 'SongImpl'. Если у вас все правильно настроено, вы можете получить исключение, сообщив вам, что' com.sun.proxy. $ Proxy ## 'не может быть передан в' SongImpl' Сначала удалите '@ Repository' из вашего dao (вы определили в XML'. Измените' SongImpl' в контроллере на 'SongDao' (программа для интерфейсов не конкретных классов). –

+0

Спасибо @ M.Deinum. просто изучаю это. – Robby

ответ

0

Похоже, что вы не настроили транзакции должным образом в своей конфигурации. This нить разрешить вокруг подобный выпуск. Также проверьте this.

Смежные вопросы

 Смежные вопросы