0

I've a simple web application with Spring MVC + Hibernate 4. But I can't insert data into MySQL, I receive the following error:

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)

My 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>

My 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);

}

My 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;
}

}

My UsuarioDAOImpl

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

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

    }


}

My Service

@Service
@Transactional
public class UsuarioService {

    @Autowired
    UsuarioDAO usuarioDao;


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

My Controller

@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";
    }

}

If I uncomment <prop key="hibernate.current_session_context_class">thread</prop> I get an error informing I can't persist because there isn't a transaction. But if I put a programmatic transaction, without annotation function. I don't understand why. Help me please I've spend so many days to solve this. I'm using Spring 3 and Hibernate 4.

Thanks!!!

davehauser
  • 5,844
  • 4
  • 30
  • 45
vtsimoes
  • 47
  • 1
  • 6

1 Answers1

0

Add this to your spring-context.xml:

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

When you add @Transactional annotation, you're using spring's declarative transaction demarcation. This transaction interceptor should be configured in a Spring container using either Java annotations or XML. This piece of configuration, did that! For more info read the manual

For new applications, always (not always!) use the latest versions. I guess it's better now to use Spring 4.2.x with Hibernate 5.x.

Also, don't put all your configurations in one place.

Community
  • 1
  • 1
Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • I've added this configuration, but problem persists. I'm using in pom java-version 1.6, spring framework 3.1.1, spring-dao 2.0.3, hibernate 4.1.7. Do you think there is a problem with dependencies versions? – vtsimoes Oct 12 '15 at 12:10
  • Nope. Your transaction configuration is the problem. Spring is using hibernate's contextual transactions, and when you call `getCurrentTransaction`, it will return that session. – Ali Dehghani Oct 12 '15 at 12:21
  • But I've included all configurations on spring-context.xml, where is the problem? What I need to modify? Thanks – vtsimoes Oct 12 '15 at 13:33