springboot整合mybatis主从数据库读取(一)

5 篇文章 0 订阅
1 篇文章 0 订阅
   前面文章已经介绍过数据库到主从复制功能,不懂到同学可以看下主从复制实现机制
也可以参考 https://blog.csdn.net/u014399489/article/details/88710429 博客,废话不多说,
直接上代码实现今天到主题课程,有错误到地方欢迎指出

一:课程到技术要求
 1)  对springboot 有一定到基础
 2)对mybatis有一定基础
 3)对maven 有一定基础
 
 二:技术应用版本
 1)eclipse   Luna Service Release 2 (4.4.2)
 2)jdk   jdk1.8.0_181
 3) springboot  2.1.1.RELEASE
 4) mybatis  1.3.2
 5)maven  3.5.0

  三:项目代码

1)springboot 是基于maven构建项目,先创建springboot工程项目
2)添加项目中用到到依赖,修改pom.xml文件

pom.xml文件内容
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<!-- 添加springboot坐标 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.1.RELEASE</version>
	</parent>
	<groupId>com.zeronode</groupId>
	<artifactId>06-springboot-mybatis-double-path</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<!-- 修改jdk依赖版本 -->
		<java.version>1.8</java.version>
		<lombok.version>1.18.6</lombok.version>
		<mybatis.version>1.3.2</mybatis.version>
		<lombox.version>1.18.6</lombox.version>
	</properties>

	<dependencies>
		<!-- 添加web启动坐标 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 添加lombok工具坐标 -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>${lombok.version}</version>
		</dependency>
		<!-- 添加springboot 测试坐标 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<!-- 添加lombox 测试坐标 -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>${lombox.version}</version>
		</dependency>
		<!-- 添加mybatis依赖坐标 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<!-- 添加mysql驱动器坐标 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!-- 添加druid数据源坐标 -->

	</dependencies>

	<build>
		<plugins>
			<!-- 依赖maven打包提示找不到主类问题 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<!-- 打包跳过测试案例代码 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.18.1</version>
				<configuration>
					<skipTests>true</skipTests>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
3) 添加sprongboot 配置文件,修改配置文件添加数据库连接信息

application.properties

#config primary datasource 
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8
spring.datasource.primary.username=root
spring.datasource.primary.password=root

#config slave datasource 
spring.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.slave.jdbc-url=jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8
spring.datasource.slave.username=root
spring.datasource.slave.password=root
  1. 编写datasource 数据源配置文件

主数据库配置config编写:PrimaryDataSourceConfig.java

package com.zeronode.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
@MapperScan(basePackages = "com.zeronode.mapper.primary", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDataSourceConfig {

	// 将这个对象放入Spring容器中,并且名称primaryDataSource
	@Bean(name = "primaryDataSource")
	// 表示这个数据源是默认数据源
	@Primary
	// 读取application.properties中的配置参数映射成为一个对象
	// prefix表示参数的前缀
	@ConfigurationProperties(prefix = "spring.datasource.primary")
	public DataSource getDataSource() {
		DataSource ds = DataSourceBuilder.create().build();
		return ds;
	}

	// 将这个对象放入Spring容器中,并且名称primarySqlSessionFactory
	@Bean(name = "primarySqlSessionFactory")
	// 表示这个数据源是默认数据源
	@Primary
	public SqlSessionFactory getSqlSessionFactory(
			@Qualifier("primaryDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// 设置primary mybatis的xml所在位置
		bean.setMapperLocations(new PathMatchingResourcePatternResolver()
				.getResources("classpath:mapper/primary/*Mapper.xml"));
		return bean.getObject();
	}

	// 将这个对象放入Spring容器中,并且名称primarySqlSessionFactory
	@Bean(name = "primarySqlSessionTemplate")
	// 表示这个数据源是默认数据源
	@Primary
	public SqlSessionTemplate getSqlSessionTemplate(
			@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlsessionFactory) {
		return new SqlSessionTemplate(sqlsessionFactory);
	}
}

主数据库mybatis到xml文件 PrimaryUserMapper.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.zeronode.mapper.primary.PrimaryUserMapper">

	<insert id="insertUser" parameterType="com.zeronode.entity.User">
		INSERT INTO USER 
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="name!= null and name != ''">
				name,
			</if>
			<if test="address != null and address != ''">
				address,
			</if>
		</trim>
		VALUES
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="name!= null and name != ''">
				#{name},
			</if>
			<if test="address != null and address != ''">
				#{address},
			</if>
		</trim>
	</insert>
</mapper>

接口类:PrimaryUserMapper.java

package com.zeronode.mapper.primary;

import com.zeronode.entity.User;

public interface PrimaryUserMapper {

	int insertUser(User user);
	
	int updateUser(User user);
	
	int deleteUser(Integer id);
	
}

从数据库配置config编写:SlaveDataSourceConfig.java

package com.zeronode.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
@MapperScan(basePackages="com.zeronode.mapper.slave",sqlSessionTemplateRef="slaveSqlSessionTemplate")
public class SlaveDataSourceConfig {

	// 标记当前为加载到spring中到类,并定于名称
	@Bean(name = "slaveDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.slave")
	public DataSource getDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "slaveSqlSessionFactory")
	public SqlSessionFactory getSqlSessionFactory(
	// 指定当前注入到DataSource时哪一个
			@Qualifier("slaveDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// 指定当前到mapper映射文件地址
		bean.setMapperLocations(new PathMatchingResourcePatternResolver()
				.getResources("classpath:mapper/slave/*Mapper.xml"));
		return bean.getObject();
	}

	@Bean(name="slaveSqlSessionTemplate")
	public SqlSessionTemplate getSqlSessionTemplate(
			// 指定当前注入到SqlSessionFactory时哪一个
			@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

从数据库到mybatis到xml配置文件:UserMapper.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.zeronode.mapper.slave.SlaveUserMapper">

	<select id="findAll" resultType="com.zeronode.entity.User">
		SELECT id,name,address from USER
	</select>
</mapper>

从数据库接口类:

package com.zeronode.mapper.slave;

import java.util.List;

import com.zeronode.entity.User;

public interface SlaveUserMapper {

	public List<User> findAll();
	
	public User findOneByName(String name);
}

实体对象:User.java

package com.zeronode.entity;

import java.io.Serializable;

import lombok.Data;

@Data
public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/** 会员主键 **/
	private Integer id;
	/** 会员姓名 **/
	private String name;
	/** 会员地址 **/
	private String address;

}

sprongboot启动类:

package com.zeronode;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages="com.zeronode.mapper")
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

项目目录结构:
在这里插入图片描述

这种方式会有重复类放在不同的路径下,继续优化中…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值