SpringBoot+Mybatis动态连接oracle和mysql
参考:https://blog.csdn.net/qq_44507798/article/details/125301020
在Spring Boot中,可以使用MyBatis实现与Oracle和MySQL等不同类型的数据库进行动态连接。下面是一个简单的示例。
首先,我们需要在pom.xml文件中添加MyBatis和Oracle、MySQL连接器的依赖项。在这个例子中,我们将使用Oracle和MySQL作为示例。
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- Oracle -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc10</artifactId>
<version>19.3.0.0</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
</dependencies>
接下来,我们需要在application.properties文件中配置Oracle和MySQL的数据库连接信息。
# Oracle Configuration
oracle.datasource.driver-class-name=oracle.jdbc.OracleDriver
oracle.datasource.url=jdbc:oracle:thin:@//hostname:port/servicename
oracle.datasource.username=username
oracle.datasource.password=password
# MySQL Configuration
mysql.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mysql.datasource.url=jdbc:mysql://hostname:port/databasename
mysql.datasource.username=username
mysql.datasource.password=password
然后,我们需要在Spring Boot应用程序中配置两个数据源。我们可以使用@Qualifier注释来区分不同的数据源。
@Configuration
public class DataSourceConfig {
@Bean(name = "oracleDataSource")
@ConfigurationProperties(prefix = "oracle.datasource")
public DataSource oracleDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "mysqlDataSource")
@ConfigurationProperties(prefix = "mysql.datasource")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
}
在此之后,我们需要配置MyBatis和两个数据源之间的映射。我们可以使用@MapperScan注释来指定mapper接口所在的包,并将其与数据源关联起来。
@Configuration
@MapperScan(basePackages = "com.example.mapper.oracle", sqlSessionFactoryRef = "oracleSqlSessionFactory")
public class OracleMyBatisConfig {
@Autowired
@Qualifier("oracleDataSource")
private DataSource oracleDataSource;
@Bean(name = "oracleSqlSessionFactory")
public SqlSessionFactory oracleSqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(oracleDataSource);
return factoryBean.getObject();
}
}
@Configuration
@MapperScan(basePackages = "com.example.mapper.mysql", sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MySqlMyBatisConfig {
@Autowired
@Qualifier("mysqlDataSource")
private DataSource mysqlDataSource;
@Bean(name = "mysqlSqlSessionFactory")
public SqlSessionFactory mysqlSqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(mysqlDataSource);
return factoryBean.getObject();
}
}
最后,我们可以在mapper接口中编写SQL语句,并使用@Mapper注释将接口与映射器关联。
@Mapper
public interface
application.properties需要将自动识别的spring.datasource改为自定义(就是加个自定义的字段给他改喽),例子在?
application.properties多加个自定义数据源,例子在?
有几个数据源就加几个数据源配置类,数据源配置类配置?
构建springboot项目,项目构建不再提…
文件目录:
dependence依赖引入
<dependencies>
<!--web相关依赖,-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis和springboot整合依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--springboot测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--最好的数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
实体类
mysql库创建的实体类
public class Student implements Serializable {
private int id;
private String name;
private String password;
private int age;
省略。。。
oracle库创建的实体类
public class Demo1 implements Serializable {
private int id;
private String name;
private String password;
省略。。。
#mybatis的配置文件路径
mybatis.config-locations=classpath:mybatis/config.xml
#mybatis的mapper映射文件地址路径
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
#mysql库1的配置
spring.datasource.primary.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/test1?serverTimezone=GMT%2B8
spring.datasource.primary.username=root
spring.datasource.primary.password=123456
#mysal库2的配置
spring.datasource.secondary.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8
spring.datasource.secondary.username=root
spring.datasource.secondary.password=123456
#oracle库的配置
spring.datasource.secondary3.driverClassName=oracle.jdbc.OracleDriver
spring.datasource.secondary3.jdbc-url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.secondary3.username=root
spring.datasource.secondary3.password=123456
@Configuration
@MapperScan(basePackages = "cn.syp.databases.mapper.mapper1", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class DataSource1Config {
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "primarySqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/StudentMapper1.xml"));
return bean.getObject();
}
@Bean(name = "primaryTransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "primarySqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
@Configuration
@MapperScan(basePackages = "cn.syp.databases.mapper.mapper2", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class DataSource2Config {
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/StudentMapper2.xml"));
return bean.getObject();
}
@Bean(name = "secondaryTransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "secondarySqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
public interface StudentMapper1 {
List<Student> findAll();
Student findOne(Integer id);
}
public interface StudentMapper2 {
List<Student> findAll2();
Student findOne2(Integer id);
}
<?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="cn.syp.databases.mapper.mapper1.StudentMapper1" > <!--指定mapper位置-->
<resultMap id="studentMap" type="cn.syp.databases.entity.Student" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>
<sql id="Base_Column_List" >id, name,password,age</sql>
<select id="findAll" resultMap="studentMap" >
SELECT
<include refid="Base_Column_List" />
FROM student
</select>
<select id="findOne" resultMap="studentMap">
SELECT * FROM student WHERE id=#{id}
</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" >
<mapper namespace="cn.syp.databases.mapper.mapper2.StudentMapper2" > <!--指定mapper位置-->
<resultMap id="studentMap" type="cn.syp.databases.entity.Student" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>
<sql id="Base_Column_List" >id, name,password,age</sql>
<select id="findAll2" resultMap="studentMap" >
SELECT
<include refid="Base_Column_List" />
FROM student
</select>
<select id="findOne2" resultMap="studentMap">
SELECT * FROM student WHERE id=#{id}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
@Controller
public class MainController {
@Autowired(required = false)
private StudentMapper1 studentMapper1;
@Autowired(required = false)
private StudentMapper2 studentMapper2;
@Autowired(required = false)
private StudentMapper3 studentMapper3;
@RequestMapping("/find")
private @ResponseBody String findAll(){
List<Student> lists = studentMapper1.findAll();
System.out.println(lists);
return lists.toString();
}
@RequestMapping("/find2")
private @ResponseBody String findAll2(){
List<Student> lists = studentMapper2.findAll2();
System.out.println(lists);
return lists.toString();
}
@RequestMapping("/find3")
private @ResponseBody String findAll3(){
List<Demo1> lists = studentMapper3.findAll3();
System.out.println(lists);
return lists.toString();
}
}