gpt4 book ai didi

java - 连接到多个数据库(n db)java spring hibernate

转载 作者:行者123 更新时间:2023-12-02 11:20:23 25 4
gpt4 key购买 nike

我想在 Spring Boot 中制作一个新的 MS,我的应用程序需要连接到多个数据库(目前有 40 个不同的服务器,但可以说 N )。我有一个API,它为我提供了我想要的数据库的用户名和密码。我想要一张数据库 map 。我只看到配置

#application.properties

dbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mydb
jdbc.username = root
jdbc.password = password
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false
<小时/>
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.springhibernate.example.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {


@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.springhibernate.example.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}

@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}

private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}

我想进行 api 调用来获取 Cardential,然后初始化数据库,可以吗?

最佳答案

尝试使用 spring 事务管理器并为每个数据库配置尽可能多的数据并定义单独的数据源,然后他能够使用 spring 和 hibernate 配置多个数据库。 enter link description here

click here to see more

关于java - 连接到多个数据库(n db)java spring hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49963955/

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