gpt4 book ai didi

java - JPA - EntityManagerFactory 指向本地主机

转载 作者:行者123 更新时间:2023-11-29 18:32:33 25 4
gpt4 key购买 nike

我有以下代码。此代码负责从远程位置连接到 MySQL 数据库。但问题是,代码正在尝试连接到本地主机上的 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());
}

问候阿努杰

最佳答案

错误信息

Access denied for user 'my_user'@'localhost_ip' (using password: YES)

并不表示您正在连接本地主机 IP 地址上的数据库,而是表示您正在本地主机的 IP 地址连接。

至于为什么您收到访问被拒绝错误:很可能您的数据库中没有与 'my_user'@'localhost_ip''my_user 匹配的用户记录'@'%'

关于java - JPA - EntityManagerFactory 指向本地主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45565625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com