SpringBoot配置多個數據庫

前言

一個SpringBoot項目對應一個數據庫,正常情況下能滿足大部分的需求。但有時因爲特殊需求,項目中要同時操作多個數據源,這時候就需要爲SpringBoot配置多個數據源。
本文以IDEA + SpringBoot + Mybatis + Mysql爲例,來實現多個數據源的訪問控制。

開始之前先看一下項目最終的目錄結構:
在這裏插入圖片描述

一. 新建SpringBoot項目

參考我的使用IDEA 搭建Spring Boot項目文章,新建一個SpringBoot項目

二. 添加第三方庫

在pom.xml中添加以下內容

        <!--mysql連接所需jar包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--mybatis所需jar包-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- alibaba JSON解析庫 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

三. 配置文件application.properties

在這裏插入圖片描述
在配置文件中添加兩個數據庫相關的參數信息,端口號我這裏設置成8081,不一定要同一臺服務器,可以不同服務器,我爲了測試方便,都連接到了本地的服務器。
紅色框部分不一定要按照圖中的寫,可以自定義(後面編寫配置類的時候要用到

四. 配置類

因爲要連接兩個數據庫,我寫了兩個配置類

@Configuration
@MapperScan(basePackages = {"com.springboot.demo.mapper.first"}, sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDBConfig {
    @Primary
    @Bean(name = "firstDataSource")
    @ConfigurationProperties(prefix="spring.datasource.first")
    public DataSource firstDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "firstSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/first/*.xml"));
        return sessionFactoryBean.getObject();
    }
}
@Configuration
@MapperScan(basePackages = {"com.springboot.demo.mapper.second"}, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDBConfig {
    @Bean(name = "secondDataSource")
    @ConfigurationProperties(prefix="spring.datasource.second")
    public DataSource secondDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/second/*.xml"));
        return sessionFactoryBean.getObject();
    }
}

其中:
prefix = 上圖中紅色框部分
basePackages = 你的項目中mapper類的目錄
getResources = 你的項目中mapper對應的xml文件
如果目錄結構和我的項目一致,可以直接複製粘貼

另外,需要在啓動類中添加紅色框部分,禁用默認的數據庫配置
在這裏插入圖片描述

五. 實體類

// 第一個數據庫中的表
@Data
public class User {
    private int id;
    private String name;
    private int age;
}
// 第二個數據庫中的表
@Data
public class Member {
    private int id;
    private String name;
    private int age;
}

六. Service類

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public List<User> getList() {
        return userMapper.getList();
    }
}
@Service
public class MemberService {
    @Autowired
    MemberMapper memberMapper;

    public List<Member> getList() {
        return memberMapper.getList();
    }
}

這裏我簡單寫了個查詢接口

七. Mapper接口

@Mapper
public interface UserMapper {
    List<User> getList();
}
@Mapper
public interface MemberMapper {
    List<Member> getList();
}

八. Mapper對應的xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--UserMapper.xml-->
<mapper namespace="com.springboot.demo.mapper.first.UserMapper">
    <resultMap id="BaseResultMap" type="com.springboot.demo.entity.first.User">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="name" jdbcType="VARCHAR" property="name"/>
        <result column="age" jdbcType="INTEGER" property="age"/>
    </resultMap>
    <select id="getList" resultMap="BaseResultMap">
        SELECT * FROM `users`
    </select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--MemberMapper.xml-->
<mapper namespace="com.springboot.demo.mapper.second.MemberMapper">
    <resultMap id="BaseResultMap" type="com.springboot.demo.entity.second.Member">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="name" jdbcType="VARCHAR" property="name"/>
        <result column="age" jdbcType="INTEGER" property="age"/>
    </resultMap>
    <select id="getList" resultMap="BaseResultMap">
        SELECT * FROM `members`
    </select>
</mapper>

注意把namespace和type的值改成你項目對應文件的路徑

九. 控制器和請求方法

@RestController
public class DemoController {
    @Autowired
    UserService userService;

    @Autowired
    MemberService memberService;

    @RequestMapping(value="/index", method = RequestMethod.GET)
    public Object index(HttpServletRequest request) {
        List<User> userList = userService.getList();
        List<Member> memberList = memberService.getList();
        JSONObject resultObj = new JSONObject();
        resultObj.put("users", userList);
        resultObj.put("members", memberList);
        return resultObj;
    }
}

這裏簡單地寫了個控制器和請求方法,分別查詢數據庫一中的用戶列表和數據庫二中的會員列表,然後返回。

十. 運行測試

運行DemoApplication,在瀏覽器中輸入http://localhost:8081/index,返回以下結果,同時查詢到兩個數據庫中兩張表的數據
在這裏插入圖片描述
2個以上數據源也是同樣的方法
完畢!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章