【问题标题】:Spring MVC + Hibernate configurationSpring MVC + Hibernate 配置
【发布时间】:2015-10-11 15:19:43
【问题描述】:

我有一个使用 Spring MVC + Hibernate 4 的简单 Web 应用程序。但我无法将数据插入 MySQL,我收到以下错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateSystemException: No CurrentSessionContext configured!; nested exception is org.hibernate.HibernateException: No CurrentSessionContext configured!
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

我的 spring-context.xml

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


    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    <context:annotation-config></context:annotation-config>

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

   <!--  -->

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.elogio.projeto" />

    <!-- Configuração do Session Factory -->
    <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <beans:property name="dataSource" ref="dataSource" />
      <beans:property name="packagesToScan" value="com.elogio.projeto.model" />
      <beans:property name="hibernateProperties">
         <beans:props>
            <beans:prop key="hibernate.hbm2ddl.auto">validate</beans:prop>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
           <!-- <beans:prop key="hibernate.current_session_context_class">thread</beans:prop> -->
         </beans:props>
      </beans:property>
   </beans:bean>


   <!-- Configuração do Transaction Manager -->
    <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <beans:property name="sessionFactory" ref="sessionFactory" />
      <beans:property name="dataSource" ref="dataSource" />
   </beans:bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

   <beans:bean id="persistenceExceptionTranslationPostProcessor"
    class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>



    <!--Configurações para o DataSource-->

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"></beans:property>
        <beans:property name="username" value="xxxxxxx"></beans:property>
        <beans:property name="password" value="xxxxxxx"></beans:property>
        <beans:property name="url" value="jdbc:mysql://localhost:3306/elogiosbd"></beans:property>
    </beans:bean>

</beans:beans>

我的 DAO

@Transactional
public interface DAO<T, I extends Serializable> {

    public T save(T entity);

    public void remove(T entity);

    public T getById(Class<T> classe, I pk);

}

我的 DAOImpl

@Repository
public abstract class DAOImpl<T, I extends Serializable> implements DAO<T, I> {

@Autowired
private SessionFactory sessionFactory;


public DAOImpl(SessionFactory sessionFactory){
    this.sessionFactory = sessionFactory;
}


@Transactional
public T save(T entity) {
    //Transaction trans = sessionFactory.getCurrentSession().beginTransaction();
    //sessionFactory.openSession().persist(entity);
    sessionFactory.getCurrentSession().saveOrUpdate(entity);
    System.out.println("Passou pelo Save");
    //trans.commit();
    return entity;

}

public void remove(T entity) {

    if (null != entity) {
        sessionFactory.getCurrentSession().delete(entity);
    }

}

@SuppressWarnings("unchecked")
public T getById(Class<T> classe, I pk) {
    T entidade = (T) sessionFactory.getCurrentSession().load(classe, (Integer) pk);
    return entidade;
}

}

我的 UsuarioDAOImpl

@Repository
@Transactional
public class UsuarioDAOImpl extends DAOImpl<Usuario, Integer> implements UsuarioDAO {

    @Autowired
    public UsuarioDAOImpl(SessionFactory sessionFactory) {
        super(sessionFactory);

    }


}

我的服务

@Service
@Transactional
public class UsuarioService {

    @Autowired
    UsuarioDAO usuarioDao;


    public void salvar(Usuario usuario){
        usuarioDao.save(usuario);
    }
}

我的控制器

@Controller
@Transactional
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * Simply selects the home view to render by returning its name.
     */

    //@Autowired
    //UsuarioDAOImpl usuarioDAO;

    @Autowired

    UsuarioService usuarioService;


    @RequestMapping(value = "/", method = RequestMethod.GET)

    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);

         Usuario usuario = new Usuario();
         usuario.setCidade("Belém");
         usuario.setEmail("xxxxxxxx");
         usuario.setEstado("PA");
         usuario.setNome("XXXXXXXXXXXXXXX");
         usuario.setSenha("12345678");


         usuarioService.salvar(usuario);


        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate);
        model.addAttribute("teste", "0035");
        return "home";
    }

}

如果我取消注释&lt;prop key="hibernate.current_session_context_class"&gt;thread&lt;/prop&gt; 我收到一条错误消息,通知我因为没有交易而无法坚持。但是如果我把一个程序化的事务,没有注释功能。我不明白为什么。请帮助我,我花了这么多天来解决这个问题。我正在使用 Spring 3 和 Hibernate 4。

谢谢!!!

【问题讨论】:

    标签: spring hibernate spring-mvc session transactions


    【解决方案1】:

    将此添加到您的 spring-context.xml:

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven />
    

    当您添加@Transactional 注释时,您正在使用spring 的声明性事务划分。此事务拦截器应使用 Java 注释或 XML 在 Spring 容器中配置。这块配置,做到了!欲了解更多信息read the manual

    对于新应用程序,始终(并非总是!)使用最新版本。我想现在最好将 Spring 4.2.x 与 Hibernate 5.x 一起使用。

    另外,don't put all your configurations in one place

    【讨论】:

    • 我已添加此配置,但问题仍然存在。我在 pom java-version 1.6、spring framework 3.1.1、spring-dao 2.0.3、hibernate 4.1.7 中使用。你觉得依赖版本有问题吗?
    • 不。您的事务配置是问题所在。 Spring正在使用hibernate的上下文事务,当你调用getCurrentTransaction时,它会返回那个会话。
    • 但是我已经在spring-context.xml中包含了所有配置,问题出在哪里?我需要修改什么?谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2017-03-19
    • 2012-01-23
    相关资源
    最近更新 更多