spirng data JPA教程(四) 双数据源的配置

spirng data JPA教程(四) 双数据源的配置

因为jpa是基于实体类的,所以双数据源的配置和mybaties 稍有不同,需要配置两套domain,两套repository

项目地址

项目的目录如下:

项目机构

DataSourceConfig.java中配置双数据源

@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @Primary
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.primary.datasource")
    public DataSource primaryDatasource() {
        System.out.println("数据源 1 连接成功");
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.secondary.datasource")
    public DataSource secondaryDataSource() {
        System.out.println("数据源 2 连接成功");
        return DataSourceBuilder.create().build();
    }
}

数据源1 PrimaryConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPrimary",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "transactionManagerPrimary", //配置 事物管理器  transactionManager
        basePackages = {"com.itguang.springbootmultidatasource.repository.test1"}//设置dao(repo)所在位置
)
public class PrimaryConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Bean(name = "entityManagerFactoryPrimary")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {

        return builder
                //设置数据源
                .dataSource(primaryDataSource)
                //设置数据源属性
                .properties(getVendorProperties(primaryDataSource))
                //设置实体类所在位置.扫描所有带有 @Entity 注解的类
                .packages("com.itguang.springbootmultidatasource.domain")
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }
    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }
    /**
     * 事物管理器
     *
     * @param builder
     * @return
     */
    @Bean(name = "transactionManagerPrimary")
    @Primary
    PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }
}

数据源2 SecondConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySecondary",
        transactionManagerRef="transactionManagerSecondary",
        basePackages= { "com.itguang.springbootmultidatasource.repository.test2" })
public class SecondaryConfig {

    @Autowired
    private JpaProperties jpaProperties;
    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;

    @Bean(name = "entityManagerSecondary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySecondary(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactorySecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(secondaryDataSource)
                .properties(getVendorProperties(secondaryDataSource))
                .packages("com.itguang.springbootmultidatasource.domain2")
                .persistenceUnit("secondaryPersistenceUnit")
                .build();
    }

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    @Bean(name = "transactionManagerSecondary")
    PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }

}

application.yml配置

spring:
  primary:
    datasource:
      url: jdbc:mysql://localhost:3306/test1?useUnicode=true
      username: root
      password: root
      driver-class-name: com.mysql.jdbc.Driver
  secondary:
    datasource:
      url: jdbc:mysql://localhost:3306/test2?useUnicode=true
      username: root
      password: root
      driver-class-name: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
      dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
server:
  port: 9999

实体类 User 对应数据库 test1 中的user表

@Data
@Entity
@Table(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable = false, unique = true)
    private String userName;
    @Column(nullable = false)
    private String passWord;
    @Column(nullable = false, unique = true)
    private String email;
    @Column(nullable = true, unique = true)
    private String nickName;
    @Temporal(TemporalType.TIMESTAMP)
    private Date regTime;

    public User() {
    }
    public User(String userName, String passWord, String email, String nickName, Date regTime) {
        this.userName = userName;
        this.passWord = passWord;
        this.email = email;
        this.nickName = nickName;
        this.regTime = regTime;
    }
}

实体类Person 对应数据库test2 中的person表

@Data
@Entity
@Table(name = "person")
public class Person implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable = false, unique = true)
    private String userName;
    @Column(nullable = false)
    private String passWord;
    @Column(nullable = false, unique = true)
    private String email;
    @Column(nullable = true, unique = true)
    private String nickName;
    @Column(nullable = false)
    private String regTime;

    public Person() {
    }
    public Person(String userName, String passWord, String email, String nickName, String regTime) {
        this.userName = userName;
        this.passWord = passWord;
        this.email = email;
        this.nickName = nickName;
        this.regTime = regTime;
    }

}

UserRepository

public interface UserRepository extends JpaRepository<User,Long> {
    User findByUserName(String userName);
    User findByUserNameOrEmail(String username, String email);
}

personRepository

public interface personRepository extends JpaRepository<Person,Long>{}

UserController 写几个简单的接口测试下

@RestController
public class UserController {
    @Resource
    private UserRepository userTest1Repository;
    @Resource
    private personRepository personRepository;
    @Resource
    private UserInfoRepository userInfoRepository;
    @GetMapping("getuser")
    public List<User> getAllUser( ){
        return userTest1Repository.findAll() ;
    }
    @GetMapping("getPerson")
    public List<Person> getAllPerson(){
        return personRepository.findAll();
    }
    @GetMapping("getUserInfo")
    public List getUserInfo(){
        return userInfoRepository.findAll();
    }
}

引入Swagger

运行项目,访问 http://localhost:9999/swagger-ui.html

测试一下:


一切 OK~
项目地址

猜你喜欢

转载自blog.csdn.net/bdqx_007/article/details/86493490
今日推荐