Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

No transactional EntityManager available

Gostaria da ajuda de vocês para resolver um problema.

Estou tentando fazer um projeto para fins didaticos de implementando SpringMVC:

eu tenho a classe AppWebConfig:

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import br.com.eponto.controller.HomeController;
import br.com.eponto.dao.RegistraDao;
import br.com.eponto.modelo.Funcionario;

@EnableWebMvc
@ComponentScan(basePackageClasses = {HomeController.class, Funcionario.class, RegistraDao.class})
public class AppWebConfiguration extends WebMvcConfigurerAdapter{

    @Bean
...

Classe de configuração do JPA:

package br.com.eponto.config;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

public class JPAConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean managerFactoryBean() {

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();

        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setUrl("jdbc:mysql://localhost:3306/epontoDB");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");

        factoryBean.setDataSource(dataSource);

            Properties props = new Properties();
            props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
            props.setProperty("hibernate.show_sql", "true");
            props.setProperty("hibernate.hbm2ddl.auto", "update");

        factoryBean.setJpaProperties(props);

        factoryBean.setPackagesToScan("br.com.eponto.modelo");

        return factoryBean;
    }

    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);

    }


}

tenho meu controller onde estou fazendo uns testes:

@Controller
@RequestMapping("/registra")
public class RegistraController {

    @Autowired
    private RegistraDao dao;

    @RequestMapping(method = RequestMethod.GET)
    public String formRegistra(){
        return "form-registra";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String registraHora() {

        HoraAtual hora = new HoraAtual();
        Calendar instance = Calendar.getInstance();
        hora.setHora(instance);

        Funcionario f1 = new Funcionario();
        f1.setCpfFunc("161561");
        f1.setIdFunc(1);
        f1.setNomeFunc("julio gouveia");
        f1.setHoraAtual(Arrays.asList(hora));

        dao.cadastra(f1);

        System.out.println(f1.getHoraAtual().get(0).getHora().getTime());
        return "redirect:/registra";
    }

e minha classe Dao:

package br.com.eponto.dao;


import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.eponto.modelo.Funcionario;

@Repository

@Transactional
public class RegistraDao {

    @PersistenceContext
    private EntityManager em;

    public void cadastra(Funcionario f1) {
        em.persist(f1);
    }


}

quando eu envio o formulário para o controller com o request para > registraHora, eu recebo uma No transactional EntityManager available.

não consigo entender por que!!! se aparentemente eu fiz todo fluxo de configuração correta.

meu DAO esta anotado com @Transactional e @Repository (importada do pacote correto), e também esta sendo scaneada pelo ComponentScan na minha AppWebConfiguration, EntityManager anotado com @PersistenceContext.

o stack tracer segue abaixo:

HTTP Status 500 - Request processing failed; nested exception is javax.persistence.TransactionRequiredException: No transactional EntityManager available

type Exception report

message Request processing failed; nested exception is javax.persistence.TransactionRequiredException: No transactional EntityManager available

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.TransactionRequiredException: No transactional EntityManager available
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
root cause

javax.persistence.TransactionRequiredException: No transactional EntityManager available
    org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:273)
    com.sun.proxy.$Proxy25.persist(Unknown Source)
    br.com.eponto.dao.RegistraDao.cadastra(RegistraDao.java:21)
    br.com.eponto.controller.RegistraController.registraHora(RegistraController.java:40)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.
2 respostas

alguem pra me dar uma luz ?

solução!

Tenta adicionar, em cima da sua classe de configuração da jpa, a annotation @EnableTransactionManagement.