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

Erro status 500 - "No transactional EntityManager available"

mport 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;
import org.springframework.transaction.annotation.EnableTransactionManagement;



@EnableTransactionManagement
public class JPAConfiguration {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory()
    {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        factoryBean.setJpaVendorAdapter(vendorAdapter);

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

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

        factoryBean.setJpaProperties(properties);
        factoryBean.setPackagesToScan("org.musify.models");

        return factoryBean;
    }

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


}

13 respostas

Dá uma olhada nesse post , acho que ele pode solucionar o seu problema https://cursos.alura.com.br/forum/topico-no-transactional-entitymanager-available-40583

Se não, me avisa que vamos tentar resolver esse problema.

Oi André boa noite,

Na minha JPA já tem esses mesmos métodos implementados, fiz exatamente como na aula do meu curso, mas mesmo assim, o erro permanece...

package org.musify.conf;

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;
import org.springframework.transaction.annotation.EnableTransactionManagement;



@EnableTransactionManagement
public class JPAConfiguration {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory()
    {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        factoryBean.setJpaVendorAdapter(vendorAdapter);

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

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

        factoryBean.setJpaProperties(properties);
        factoryBean.setPackagesToScan("org.musify.models");

        return factoryBean;
    }

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


}

Tenta adicionar @Transactional nas suas classes e métodos

Oi André, obrigada pela ajuda. Eu coloquei em todas, mas deu erro na JPA então retirei somente nela e deixei nas demais, mas aparece o erro "Error creating bean with name 'internalResourceViewResolver' defined in class org.musify.conf.AppWebConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.view.InternalResourceViewResolver org.musify.conf.AppWebConfiguration.internalResourceViewResolver()] threw exception; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection"

Hum, posta o código novo pra gente ver como ficou.

Segue André

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;
import org.springframework.transaction.annotation.EnableTransactionManagement;



@EnableTransactionManagement
public class JPAConfiguration {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory()
    {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        factoryBean.setJpaVendorAdapter(vendorAdapter);

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("");
        dataSource.setUrl("jdbc:mysql://localhost:3306/musify");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        factoryBean.setDataSource(dataSource);
    JPA Configuration:    
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.hbm2ddl.auto", "update");

        factoryBean.setJpaProperties(properties);
        factoryBean.setPackagesToScan("org.musify.models");

        return factoryBean;
    }

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


}

***Classe DAO

package org.musify.dao;

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

import org.musify.models.Artista;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository



public class ArtistaDAO {

    @PersistenceContext
    private EntityManager manager;
    @Transactional
    public void gravar(Artista artista)
    { 
        manager.persist(artista);
    }
}


****Controller
package org.musify.controllers;

import org.musify.dao.ArtistaDAO;
import org.musify.models.Artista;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
@Transactional
@Controller
public class ArtistasController {

    @Autowired
    private ArtistaDAO dao;
    @RequestMapping("/artistas/form")
    public String form() {
        return "artistas/form";
    }

    @RequestMapping("/artistas")
    public String gravar( Artista artista)
    {
        System.out.println(artista);
        dao.gravar(artista); 
        return "artistas/ok";
    }
}

Olá Samantha, Poderia me mostrar seu AppWebConfiguration?

Oi Clovis, claro mando sim. Obrigada pela ajuda.

package org.musify.conf;

import org.musify.controllers.HomeController;
import org.musify.dao.ArtistaDAO;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@EnableWebMvc
@ComponentScan(basePackageClasses={HomeController.class, ArtistaDAO.class})
public class AppWebConfiguration {

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver () {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

Tente mudar seu ArtistaDAO para :

@Repository
@Transational
public class ArtistaDAO {

    @PersistenceContext
    private EntityManager manager;

    public void gravar(Artista artista)
    { 
        manager.persist(artista);
    }
}

Seu Controller para:

@Controller
public class ArtistasController {

    @Autowired
    private ArtistaDAO dao;
    @RequestMapping("/artistas/form")
    public String form() {
        return "artistas/form";
    }

    @RequestMapping("/artistas")
    public String gravar( Artista artista)
    {
        System.out.println(artista);
        dao.gravar(artista); 
        return "artistas/ok";
    }
}

Oi Clovis, segui as orientações e apareceu novamente o erro 500 com essa mensagem: "Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection"

Samantha bom dia, tenta colocar um sysout e ver se entra nesse método por favor:

@Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
          System.out.println("Criando transação");
      return new JpaTransactionManager(emf);
    }
solução!

Entrar ele entra "nov 18, 2018 2:01:39 PM org.apache.catalina.core.ApplicationContext log INFORMAÇÕES: Initializing Spring FrameworkServlet 'dispatcher' Criando transação nov 18, 2018 2:01:42 PM org.apac"

Só pra manter organizado. O problema foi solucionado com a seguinte solução encontrada pela Samantha: "Eu consegui fazer funcionar, nesse caso, eu tive que informar a senha do banco de dados na classe JPA: dataSource.setPassword("root");. Aí funcionou, não é uma boa p´ratica, mas para dar seguimento ao curso me ajudou. Obrigada a todos pela atenção!!!"