Mysql 在springboot中使用多数据库

Mysql 在springboot中使用多数据库,mysql,database,spring,Mysql,Database,Spring,当我想在两个数据库之间工作时遇到了一个问题,我想使用数据库1中的表1和数据库2中的表2,我尝试了很多方法,但似乎都不起作用 spring.datasource.primary.url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8 spring.datasource.primary.username = root spring.datasource.primary.password =

当我想在两个数据库之间工作时遇到了一个问题,我想使用数据库1中的表1和数据库2中的表2,我尝试了很多方法,但似乎都不起作用

spring.datasource.primary.url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8
spring.datasource.primary.username = root
spring.datasource.primary.password = xxxx
spring.datasource.primary.driverClassName=com.mysql.jdbc.Driver

spring.datasource.secondary.url = jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=UTF-8
spring.datasource.secondary.username = root
spring.datasource.secondary.password = xxxx
spring.datasource.secondary.driverClassName=com.mysql.jdbc.Driver
以上是我的application.properties。然后我使用@Primary设置spring.datasource.Primary作为配置文件中的主数据库

@Entity
@Table(name = "User")
public class User {
    @Id
    @NotNull
    @Column(name = "phoneid")
    private String  phoneid;
}
public interface UserDAO extends CrudRepository<User, String> {
    public User findByPhoneid(String phoneid);
}
@实体
@表(name=“User”)
公共类用户{
@身份证
@NotNull
@列(name=“phoneid”)
私有字符串音素;
}
公共接口UserDAO扩展了crudepository{
公共用户findByPhoneid(字符串phoneid);
}
我想连接到数据库spring.datasource.primary并在其中使用表User

@Entity
@Table(name = "Favorite_Restaurant")
public class FavoriteRestaurant {
    @Id
    @NotNull
    @Column(name = "favorite_restaurantid")
    private int favoriteRestaurantId;
}
public interface FavoriteRestaurantDAO extends JpaRepository<FavoriteRestaurant, Integer> {

public List<FavoriteRestaurant> findAll(Sort sort);
}
@实体
@表(name=“最喜欢的餐厅”)
公共餐厅{
@身份证
@NotNull
@列(name=“favorite\u restaurantid”)
私人餐厅;
}
公共界面FavoriteRestaurantDAO扩展了JpaRepository{
公共列表findAll(排序);
}
我想连接到数据库spring.datasource.secondary并使用其中的表FavoriteStaurant


然而,当我在我的服务中自动连接UserDAo和FavoriteRestaurantDAO时,看起来就像它从主数据库自动连接UserDAo和FavoriteRestaurantDAO一样。如何从辅助数据库注入FavoriteRestaurantDAO!!!!!救命啊

要能够使用多个数据源,您需要有多个持久单元配置

我假设您已经有了要配置的
datasourceA
datasourceB

我们的每个持久单元都有一个配置类。该列表包含
datasourceA
的类(您必须复制并调整
datasourceB
的配置)

最好不要将来自不同持久单元的实体混合在一起。 因此,我们根据包装将它们分开。我们创建了一个空类
SpringRootPackageMarker
以便它告诉spring要扫描哪些包

注意
@enableJParepositions
GetDataSourceEntityManagerFactoryBean
方法中都使用
SpringRootPackageMarker

这就是我们的方法:

@DependsOn("transactionManager")
@EnableJpaRepositories(
        basePackageClasses = SpringRootPackageMarker.class,
        entityManagerFactoryRef = "datasourceAEntityManager",
        transactionManagerRef = "transactionManager")
public class DatasourceAPersistenceUnitConfiguration {


    private static final String DATASOURCE_A_PERSISTENT_UNIT_NAME = "datasourceAPU";


    @DependsOn("transactionManager") // for unit tests
    @Bean(name = "datasourceAEntityManager")
    public LocalContainerEntityManagerFactoryBean getDatasourceAEntityManagerFactoryBean() {
        final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setPersistenceUnitName(DATASOURCE_A_PERSISTENT_UNIT_NAME);
        factory.setDataSource(getDatasourceA());
        factory.setJpaVendorAdapter(getDatasourceAJpaVendorAdapter());
        factory.setPackagesToScan(SpringRootPackageMarker.class.getPackage().getName());
        Properties jpaProperties = getDatasourceAJpaProperties();
        factory.setJpaProperties(jpaProperties);
        return factory;
    }

    @Bean
    public DataSource getDatasourceA() {

        DataSource datasource = null;
        // prepare datasource A;

        return datasource;
    }


    private JpaVendorAdapter getDatasourceAJpaVendorAdapter() {
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        //custom configuration for datasource A

        return vendorAdapter;
    }


    private Properties getDatasourceAJpaProperties() {
        Properties jpaProperties = new Properties();

        //custom properties

        return jpaProperties;
    }
}

}
如果您计划将entityManager注入到应用程序中,则必须采用以下方式:

@PersistenceContext(unitName= DatasourceAPersistenceUnitConfiguration.DATASOURCE_A_PERSISTENT_UNIT_NAME)
private EntityManager manager;

最后,我通过在配置类上方添加@EnableAutoConfiguration解决了这个问题

@Configuration
@EnableJpaRepositories(basePackages = "datamodel.dao", entityManagerFactoryRef = "localEntityManagerFactory", transactionManagerRef = "localTransactionManager")
@EnableTransactionManagement
@EnableAutoConfiguration  ///the key to make spring boot know your config!!!!!!!!!!!!!
public class MainDataConfig {
@Bean
@ConfigurationProperties(prefix = "datasource.main")
@Primary
public DataSource localDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@Primary
public LocalContainerEntityManagerFactoryBean localEntityManagerFactory(final EntityManagerFactoryBuilder builder) {
    return builder.dataSource(localDataSource()).packages("datamodel.domain")
        .persistenceUnit("mainPersistenceUnit").build();
}

@Bean
@Primary
public JpaTransactionManager localTransactionManager(@Qualifier("localEntityManagerFactory") final EntityManagerFactory factory) {
    return new JpaTransactionManager(factory);
}
}

请检查这个链接,看看它是否有帮助谢谢,我终于知道出了什么问题!!!我在config类上方缺少@EnableAutoConfiguration,稍后我将提出解决方案