Spring,Hibernate,WebApplication:无法获取当前线程的事务同步会话

时间:2016-08-20 04:44:00

标签: java xml spring hibernate spring-mvc

我查看了几乎所有关于某个搜索引擎给我的主题的链接,但我似乎无法弄清楚我的问题。每当尝试执行Hibernate命令时,我都会收到错误

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

我添加了

<tx:annotation-driven />

以及

@Transactional

到我的服务和我的Dao,但它仍然出现。 这些是我的文件:

AccountDao.java

@Repository
@Transactional
public class AccountDao extends AbstractDaoImpl<Account, Long> {
    public Account getAccountByUsername(String username) {
        Criteria c = getSession().createCriteria(Account.class);
        c.add(Restrictions.eq("username", username));
        Account a = (Account) c.uniqueResult();

        return a;
    }
}

AccountService.java

@Service
@Transactional
public class AccountService {
    private static Logger log = Logger.getLogger(AccountService.class);

    @Autowired
    private AccountDao accountDao;

    public Account getAccountByUsername(String username) {
        return accountDao.getAccountByUsername(username);
    }
}

AccountController.java

@Controller
@RequestMapping(value = "/account")
public class AccountController {
    private static Logger log = Logger.getLogger(AccountController.class);

    @Autowired
    public AccountService accountService;

    @RequestMapping(value="/user/{name}", method = RequestMethod.GET)
    public String onShow(Model model, @PathVariable String name, HttpServletRequest request) throws Exception {
        log.info("Showing Account");

        Account account = accountService.getAccountByUsername(name);
        model.addAttribute("account", account);

        return "account";
    }
}

serviceBeans.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <task:annotation-driven/>

    <bean id="hibernateStringEncryptor" class="org.jasypt.hibernate4.encryptor.HibernatePBEStringEncryptor">
        <property name="registeredName" value="strongHibernateStringEncryptor"/>
        <property name="algorithm" value="PBEWithMD5AndTripleDES"/>
        <property name="password" value="jasypt"/>
    </bean>

    <bean id="accountService" class="de.appsiting.bvdg.service.AccountService">
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <!-- *** TX LAYER -->
    <tx:annotation-driven  proxy-target-class="true" transaction-manager="txManager" />

    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:advice id="tx.advice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="false"/>
        </tx:attributes>
    </tx:advice>

    <!-- *** AOP -->
    <aop:config>
        <aop:pointcut id="accountServiceMethods"
                      expression="execution(* de.appsiting.bvdg.service.AccountService.*(..))"/>

        <aop:advisor advice-ref="tx.advice" pointcut-ref="accountServiceMethods"/>
    </aop:config>
</beans>

webApplicationContext.xml

<?xml version="1.0" encoding="windows-1252"?>
<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:mvc="http://www.springframework.org/schema/mvc"
       xmlns="http://www.springframework.org/schema/beans"
       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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

    <context:component-scan base-package="de.appsiting"/>

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.springframework.web.servlet.PageNotFound">pageNotFound</prop>
                <prop key="org.springframework.dao.DataAccessException">dataAccessFailure</prop>
                <prop key="org.springframework.transaction.TransactionException">dataAccessFailure</prop>
            </props>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

    <mvc:annotation-driven/>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="validationMessageSource" ref="messageSource"/>
    </bean>

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
            p:basename="messages" />

    <bean id="messageAccessor" class="org.springframework.context.support.MessageSourceAccessor">
        <constructor-arg index="0" ref="messageSource"/>
    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" id="WebApp_ID"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>bvdg-webapp</display-name>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Spring framework -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:propertyOverride.xml
            classpath:serviceBeans.xml
            classpath:dataAccess.xml
            /WEB-INF/securityCommon.xml
            /WEB-INF/webApplicationConfig.xml
        </param-value>
    </context-param>

    <!-- Encoding Filter -->
    <filter>
        <filter-name>encoding-filter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding-filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- BO security section -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- EO security section -->
    <servlet>
        <servlet-name>bvdg</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/webApplicationConfig.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>bvdg</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
    </error-page>

    <error-page>
        <error-code>400</error-code>
        <location>/error.jsp</location>
    </error-page>
</web-app>

dataAccess.xml

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

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://127.0.0.1:5432/bvdg"/>
        <property name="username" value="bvdg"/>
        <property name="password" value="bvdg"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

        <property name="dataSource" ref="dataSource"/>

        <property name="mappingResources">
            <list>
                <value>de/appsiting/bvdg/model/Account.hbm.xml</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.PostgreSQL9Dialect
                </prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.use_sql_comments">true</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

    </bean>

    <bean id="genericDao" abstract="true">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="accountDao" class="de.appsiting.bvdg.persistence.AccountDao" parent="genericDao"/>
</beans>

也许其中一个人可以找到错误。我现在一直在看我的代码约5小时。

提前致谢

//编辑:添加了AbstractDaoImpl,从中继承了AccountDao。

AbstractDaoImpl.java

@Transactional(value = "txManager")
public class AbstractDaoImpl<T, ID extends Serializable> implements AbstractDao<T, ID> {
    @SuppressWarnings("unchecked")
    private Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    @Autowired
    @Resource(name = "sessionFactory")
    @Inject
    private SessionFactory sessionFactory;

    public AbstractDaoImpl() {
    }

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

    @SuppressWarnings({"unchecked", "hiding"})
    private <STL> List<STL> _all(Class<STL> type) {
        return getSession().createCriteria(type).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public T get(ID id) {
                              return getSession().get(persistentClass, id);
                                                                           }

    @SuppressWarnings("unchecked")
    @Override
    public ID save(T entity) {
                                   return (ID) getSession().save(entity);
                                                                         }

    @Override
    public void update(T entity) {
                                       getSession().update(entity);
                                                                   }

    @Override
    public void delete(T entity) {
                                       getSession().delete(entity);
                                                                   }

    @Override
    public List<T> findAll() {
                                   return _all(persistentClass);
                                                                }

    public SessionFactory getSessionFactory() {
                                                    return this.sessionFactory;
                                                                               }

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

1 个答案:

答案 0 :(得分:0)

先生,你好,我想你错过了你的xml文件中绑定的会话工厂。 我希望这会对你有所帮助..谢谢先生:)祝你有个美好的一天..

@Repository @Transactional

公共类AccountDao扩展了AbstractDaoImpl {

/* This part is missing in your code thats why there are no such connection between  your Dao and your dataAcess xml. */
@Autowired
private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

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

public Account getAccountByUsername(String username) {
    // this part is missing also this will bind the session from dataAcess.xml
    Session session = this.sessionFactory.getCurrentSession();
    Criteria c = session.createCriteria(Account.class);
    c.add(Restrictions.eq("username", username));
    Account a = (Account) c.uniqueResult();

    return a;
} 

}