应用场景:在同一个应用中有时候不仅仅需要访问一个的数据库,还需要连接多个数据库,这个时候就需要通过配置多个数据源来满足应用场景。
使用JPA来操作数据库,引入依赖:
spring-boot-starter-data-jpa
1、创建两个数据库,并建立对应的表t_user
2、项目目录结构:
3、在application.properties中配置两个数据源:
spring.datasource.primary.jdbc-url = jdbc:mysql://127.0.0.1:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.primary.username = admin spring.datasource.primary.password = admin spring.datasource.primary.driver-class-name = com.mysql.cj.jdbc.Driver spring.datasource.secondary.jdbc-url = jdbc:mysql://127.0.0.1:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.secondary.username = admin spring.datasource.secondary.password = admin spring.datasource.secondary.driver-class-name = com.mysql.cj.jdbc.Driver #SQL输出 spring.jpa.show-sql=true
#注意这个地方是update不是create,如果是create会发现每次都会把之前的数据删除掉。 spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect #format 以下SQL进行输出 spring.jpa.properties.hibernate.format_sql=true
3、建立实体类User
package com.example.jtademo.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; /** * @Auther: ecchen * @Date: 2019/12/11 13:39 * @Description: */ @Entity(name = "t_user") @Data @Builder @AllArgsConstructor @NoArgsConstructor public class User { @Id private Long id; @Column(name = "user_name",nullable = false,unique = true) private String userName; @Column(name = "password",nullable = false) private String passWord; @Column(name = "email",nullable = false,unique = true) private String email; @Column(name = "nick_name",nullable = false,unique = true) private String nickName; @Column(name = "reg_time",nullable = false) private String regTime; }
4、建立repository1,repository2一样。
package com.example.jtademo.repository.test1; import com.example.jtademo.model.User; import org.springframework.data.jpa.repository.JpaRepository; /** * @Auther: ecchen * @Date: 2019/12/11 11:20 * @Description: */ public interface UserTest1Repository extends JpaRepository<User,Long> { }
5、建立配置类DataSourceConfig,在项目启动时运行初始化数据库资源。
@Configuration public class DataSourceConfig { @Autowired private JpaProperties jpaProperties; @Autowired private HibernateProperties hibernateProperties; @Bean(name = "primaryDataSource") @Primary @ConfigurationProperties("spring.datasource.primary") public DataSource firstDataSource(){ return DataSourceBuilder.create().build(); } @Bean(name = "secondaryDataSource") @ConfigurationProperties("spring.datasource.secondary") public DataSource secondaryDataSource(){ return DataSourceBuilder.create().build(); } @Bean(name = "vendorProperties") public Map<String,Object> getVendorProperties(){ return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(),new HibernateSettings()); } }
6、建立默认数据源配置类PrimaryConfig,将配置文件中的信息注入到类中
@Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactoryPrimary", transactionManagerRef = "transactionManagerPrimary", basePackages = {"com.example.jtademo.repository.test1"} ) public class PrimaryConfig { @Autowired @Qualifier("primaryDataSource") private DataSource primaryDataSource; @Autowired @Qualifier("vendorProperties") private Map<String,Object> vendorProperties; @Bean(name = "entityManagerFactoryPrimary") @Primary public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder){ return builder .dataSource(primaryDataSource) .properties(vendorProperties) .packages("com.example.jtademo.model") .persistenceUnit("primaryPersistenceUnit") .build(); } @Bean(name = "entityManagerPrimary") @Primary public EntityManager entityManager(EntityManagerFactoryBuilder builder){ return entityManagerFactoryPrimary(builder).getObject().createEntityManager(); } @Bean(name = "transactionManagerPrimary") @Primary PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder){ return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject()); } }
最后一步@EnableJpaRepositories最为关键,将我们在类中配置好的 EntityManager 和事务信息注入到对应数据源的 repository 目录下,这样此目录下的 repository 就会拥有对应数据源和事务的信息。
EntityManager是JPA中负责数据库增删改查的接口类,basePackages可以支持多个repository的连写,以逗号分隔。
SecondaryConfig和PrimaryConfig雷同,不同点在于没有@Primary注解。
至此,编码完成,可以编写测试类来验证了。
测试类如下:
@Test public void testJpaSaveMethod(){ User user1 = new User(); user1.setId(3L); user1.setUserName("ec_chen6"); user1.setEmail("345116@email.com"); user1.setNickName("昵称6"); user1.setPassWord("1452146"); user1.setRegTime("2019-12-16"); userTest1Repository.save(user1); User user2 = new User(); user2.setId(3L); user2.setUserName("ec_chen3"); user2.setEmail("3451@email24.com"); user2.setNickName("昵称235"); user2.setPassWord("14521455"); user2.setRegTime("2019-12-15"); userTest2Repository.save(user2); }
运行结果如下:
运行测试类成功,数据库分别存入一条数据。