1. 配置数据源

在application.properties中配置数据源:

# 数据源1
spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/orcl
spring.datasource.username=username1
spring.datasource.password=password1
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

# 数据源2
spring.datasource.second.url=jdbc:oracle:thin:@//localhost:1521/orcl2
spring.datasource.second.username=username2
spring.datasource.second.password=password2
spring.datasource.second.driver-class-name=oracle.jdbc.driver.OracleDriver
  1. 配置MyBatis

在application.properties中配置MyBatis:

# MyBatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.entity
  1. 配置Mapper接口

创建Mapper接口:

package com.example.mapper;

import com.example.entity.User;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {
    User getUserById(@Param("id") Long id);
}

创建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">

<mapper namespace="com.example.mapper.UserMapper">

    <select id="getUserById" resultType="com.example.entity.User">
        SELECT * FROM user WHERE id = #{id}
    </select>

</mapper>
  1. 配置多数据源

创建数据源1对应的SqlSessionFactory:

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@Primary
public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath:mapper/*.xml"));
    return sessionFactory.getObject();
}

创建数据源2对应的SqlSessionFactory:

@Bean(name = "secondSqlSessionFactory")
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource secondDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean(name = "secondSqlSessionFactory")
public SqlSessionFactory secondSqlSessionFactory() throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(secondDataSource());
    sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath:mapper/*.xml"));
    return sessionFactory.getObject();
}
  1. 使用Mapper接口访问数据库

在需要使用数据源1的地方,注入UserMapper:

@Autowired
private UserMapper userMapper;

在需要使用数据源2的地方,注入UserMapper并使用@Qualifier指定SqlSessionFactory:

@Autowired
@Qualifier("secondSqlSessionFactory")
private UserMapper userMapper;

注:@Qualifier指定的是SqlSessionFactory的bean名称,即@Bean注解的name属性

springboot如何配置oracle多数据源mybatis使用mapper接口访问数据库。

原文地址: https://www.cveoy.top/t/topic/gpmp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录