无法为事务打开JPA EntityManager。

13 浏览
0 Comments

无法为事务打开JPA EntityManager。

我正在尝试使用Hibernate建立一个JPA连接,但是我不知道我的代码有什么问题。

我的配置:

@EnableTransactionManagement
public class JPAConfig {
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean =
                new LocalContainerEntityManagerFactoryBean();
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
        DriverManagerDataSource driverManagerDataSource =
                new DriverManagerDataSource();
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("");
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/odontology");
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        localContainerEntityManagerFactoryBean.setDataSource(driverManagerDataSource);
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        localContainerEntityManagerFactoryBean.setJpaProperties(properties);
        localContainerEntityManagerFactoryBean.setPackagesToScan("org.odontology.models");
        return localContainerEntityManagerFactoryBean;
    }
    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){
        return new JpaTransactionManager(entityManagerFactory);
    }
}

这是我收到的错误:

    org.springframework.transaction.CannotCreateTransactionException: 无法为事务打开JPA EntityManager;嵌套异常为javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: 无法打开连接

0
0 Comments

在使用JPA EntityManager进行事务操作时,出现了“Could not open JPA EntityManager for transaction”的错误。这个错误的原因可能是因为在设置密码时,传入了空字符串""。可以尝试不调用driverManagerDataSource.setPassword方法,或者将其设置为null。

另外,还可以参考这个问题的解决方法:Mysql Connection with out password using corejava program

0