我有以下代码。此代码负责从远程位置连接到MySQL数据库。但问题是,代码试图在localhost上连接到MySQL。
收到的实际例外是: 引起:java.sql.SQLException:用户'my_user'@'localhost_ip'拒绝访问(使用密码:YES)
我在项目中使用Spring,JPA和hibernate。
@Configuration("persistenceContext")
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "jpaTransactionManager",
basePackages = {"my.repository"})
@EnableTransactionManagement
public class PersistenceContext {
@Autowired
private DataSourcePropertyConfig dataSourcePropertyConfig;
public BasicDataSource datasource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(dataSourcePropertyConfig.getMySqlDriverClassName());
dataSource.setUsername(dataSourcePropertyConfig.getMySqlDBUsername());
dataSource.setPassword(dataSourcePropertyConfig.getMySqlDBPassword());
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");
return dataSource;
}
public JpaVendorAdapter jpaVendorAdapter() {
final HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(false);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
return hibernateJpaVendorAdapter;
}
@Bean(name = "entityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(this.datasource());
entityManagerFactoryBean.setJpaVendorAdapter(this.jpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("my.entity");
entityManagerFactoryBean.afterPropertiesSet();
return entityManagerFactoryBean.getObject();
}
@Bean(name = "jpaTransactionManager")
@Primary
public PlatformTransactionManager jpaTransactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
此致 Anuj
答案 0 :(得分:0)
错误消息
用户'my_user'@'localhost_ip'拒绝访问(使用密码:是)
并不表示您将连接到本地主机的IP地址上的数据库,这表示您正在连接来自您的localhost的IP地址。
至于您获得拒绝访问权限的原因:您的数据库中很可能没有与'my_user'@'localhost_ip'
或'my_user'@'%'
匹配的用户记录。