栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

基于注解实现SpringBoot多数据源配置

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于注解实现SpringBoot多数据源配置

1.功能介绍

在实际的开发中,同一个项目中使用多个数据源是很常见的场景。最近在学习的过程中使用注解的方式实现了一个Springboot项目多数据源的功能。具体实现方式如下。

2.在application.properties中添加多数据源配置

添加多个数据源和mapper文件路径配置,此配置用于基于java的配置数据源中使用。

#数据库配置spring.datasource.demo.user.url=jdbc:mysql://xxx.xx.xx.xx:3306/demo-userspring.datasource.demo.user.username=xxxx
spring.datasource.demo.user.password=xxxx
spring.datasource.demo.user.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.demo.server.url=jdbc:mysql://xxx.xx.xx.xx:3306/springbootdemospring.datasource.demo.server.username=xxxx
spring.datasource.demo.server.password=xxxx
spring.datasource.demo.server.driver-class-name=com.mysql.jdbc.Driver#mapper文件的路径mybatis.demo.server.mapper-location=classpath*:mapper/demo-server
    List list();

}

mapper文件如下:



    
        SELECT `name` FROM `user`    

定义读取springbootdemo数据库的接口,代码如下。使用DemoServerMapper注解表识

@DemoServerMapperpublic interface DictionaryDao {    
    List list();    
    List listChildrenByKey(String key);    
    void insert(Dictionary dictionary);

}

mapper文件代码如下:



    
        
        
        
        
        
    

    
        SELECT * FROM `dictionary`    

    
        SELECT * FROM dictionary where parent_id= (select id from dictionary where dict_key= #{key})    

    
        delete from dictionary where id = #{id}    

    
        INSERT INTO `dictionary`(`dict_key`,`dict_value`,`parent_id`,`description`)
        VALUES(#{dictKey}, #{dictValue}, #{parentId}, #{description})    
5.定义注解

定义DemoUserMapper和DemoServerMapper注解,分别作为使用demo-user和springbootdemo数据库的表识。
定义代码如下:

@documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Component@Mapperpublic @interface DemoServerMapper {    
    String value() default "";
}@documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Component@Mapperpublic @interface DemoUserMapper {    
    String value() default "";
}
6.使用单元测试验证配置

编写单元测试代码如下:

@RunWith(SpringRunner.class)@SpringBootTestpublic class MultiDatasourceApplicationTests {

    @Autowired
    private DictionaryDao dictionaryDao;    @Autowired
    private UserDao userDao;    @Test
    public void contextLoads() {
        System.out.println(dictionaryDao.list());
        System.out.println("===================");
        System.out.println(userDao.list());
    }

}

原文出处

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/234988.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号