SpringBoot如何整合SpringMVC的拦截器、数据源、Mybatis以及配置多数据源?

64 阅读4分钟

添加数据库连接池的配置 在这里插入图片描述

三、整合Mybait

pom

需要MySQL驱动依赖

mysql mysql-connector-java org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.0

Controller

package com.lsh.controller;

import com.lsh.model.Label; import com.lsh.service.Impl.MapperService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;

import java.util.List;

/**

  • @author :LiuShihao
  • @date :Created in 2020/11/5 3:13 下午
  • @desc : */ @RequestMapping("/mybatis") @RestController public class BaseMapperController { @Autowired MapperService service; @GetMapping public List findAll(){ return service.findAll(); } @GetMapping("/id") public Label findById(String id){ return service.findById(id); } @GetMapping("/findByKeyword") public List findByKeyword(String labelname){ return service.findByKeyword(labelname); } @PostMapping("/findByKeywords") public List findByKeywords(@RequestBody Label label){ return service.findByKeywords(label); } @PostMapping public void add(@RequestBody Label label){ service.add(label); } @PutMapping public void update(@RequestBody Label label){ service.upadte(label); } @DeleteMapping public void del(String id){ service.deleteById(id); } }

Service

package com.lsh.service.Impl;

import com.lsh.mapper.BaseMapper; import com.lsh.model.Label; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

import java.util.List;

/**

  • @author :LiuShihao
  • @date :Created in 2020/11/5 3:07 下午
  • @desc : */ @Service public class MapperService { @Autowired BaseMapper baseMapper;

public List findAll(){ return baseMapper.findAll(); } public Label findById(String id){ return baseMapper.findById(id); } public List findByKeyword(String label){ return baseMapper.findByKeyword(label); } public List findByKeywords(Label label){ return baseMapper.findByKeysords(label.getLabelname(),label.getFans()); } public void add(Label label){ baseMapper.addLabel(label); } public void upadte(Label label){ baseMapper.updateLabel(label); } public void deleteById(String id){ baseMapper.deleteById(id); } }

Mapper 接口(直接使用注解)

package com.lsh.mapper;

import com.lsh.model.Label; import org.apache.ibatis.annotations.*;

import java.util.List;

/**

  • @author :LiuShihao
  • @date :Created in 2020/11/5 2:22 下午
  • @desc : / //该注解说明该类就行相当于一个xxxMapper.xml文件 @Mapper public interface BaseMapper { @Select("SELECT * FROM tb_label") List findAll(); @Select("SELECT * FROM tb_label WHERE id = #{id}") Label findById(String id); /*
  • 模糊查询 -
  • 因为#{} 取值出会自带引号,${}取值就是去除原值,当参数是基本数据类型,其中必须是value
  • @param labelname
  • @return / @Select("SELECT * FROM tb_label WHERE labelname LIKE '%${value}%'") List findByKeyword(String labelname); /*
  • Mapper接口方法中多个参数,想要注入到SQL语句中,需要使用注解@Param
  • @param labelname
  • @param fans
  • @return / @Select("SELECT * FROM tb_label WHERE labelname LIKE '%labelname{labelname}%' AND `fans` LIKE '%{fans}%'") List findByKeysords(@Param("labelname") String labelname,@Param("fans") String fans); /*
  • 添加
  • @param label / @Insert("INSERT INTO tb_label VALUES (#{id},#{labelname},#{state},#{count},#{recommend},#{fans})") void addLabel (Label label); /*
  • 更新
  • @param label / @Update("UPDATE tb_label SET labelname = #{labelname} ,state = #{state},count=#{count},recommend=#{recommend},fans=#{fans} WHERE id = #{id}") void updateLabel(Label label); /*
  • 删除
  • @param id */ @Delete("DELETE FROM tb_label WHERE id = #{id}") void deleteById(String id); }

使用mapper.xml配置文件形式

mybatis-config.xml配置文件

写mybatis-config.xml配置文件,放在/resources/mybatis/

Mapper接口

UserMapper

public interface UserMapper { List findAllLabelByMapperXML() ; }

BaseMapper

public interface BaseMapper {

List findAllLabelByMapperXML(); }

Mapper映射文件

SELECT * FROM `tb_label` select * from `tb_user`

yml配置文件

server: port: 9001 spring: application: name: tensquare-base # 服务名字,用于服务调用.不能写_ springcloud不识别 datasource: db1: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://116.62.13.104:3306/tensquare_base?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF8 username: root password: 123456 db2: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://116.62.13.104:3306/tensquare_user?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF8 username: root password: 123456 eureka: client: service-url: defaultZone: http://localhost:6868/eureka mybatis: type-aliases-package: com.lsh.model.* mapper-locations: classpath:mybatis/mapper/**.xml config-location: classpath:mybatis/mybatis-config.xml

四、配置多数据源

结构

[图片上传失败...(image-a58487-1604660537654)]

第一个数据源Config配置类

package com.lsh.config;

import lombok.extern.slf4j.Slf4j; 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;

import javax.sql.DataSource;

/**

  • @author :LiuShihao
  • @date :Created in 2020/6/22 5:17 下午
  • @desc :数据源配置类 */ @Slf4j //表示这个类为一个配置类 @Configuration // 配置mybatis的接口类放的地方 @MapperScan(basePackages = "com.lsh.mapper.db1", sqlSessionFactoryRef = "test1SqlSessionFactory") public class DataSourceConfig1 { // 将这个对象放入Spring容器中 @Bean(name = "test1DataSource") // 表示这个数据源是默认数据源 @Primary // 读取application.properties中的配置参数映射成为一个对象 // prefix表示参数的前缀 @ConfigurationProperties(prefix = "spring.datasource.db1") public DataSource getDateSource1() { return DataSourceBuilder.create().build(); } @Bean(name = "test1SqlSessionFactory") // 表示这个数据源是默认数据源 @Primary // @Qualifier表示查找Spring容器中名字为test1DataSource的对象 public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(datasource); bean.setMapperLocations( // 设置mybatis的xml所在位置 new PathMatchingResourcePatternResolver().getResources("mybatis/mapper/db1/**.xml")); return bean.getObject(); } @Bean("test1SqlSessionTemplate") // 表示这个数据源是默认数据源 @Primary public SqlSessionTemplate test1sqlsessiontemplate( @Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionfactory) { return new SqlSessionTemplate(sessionfactory); } public DataSourceConfig1(){ log.info("加载1数据源配置"); } }

第二个数据源Config配置类

package com.lsh.config;

import lombok.extern.slf4j.Slf4j; 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;

import javax.sql.DataSource;

/**

  • @author :LiuShihao
  • @date :Created in 2020/6/22 5:17 下午
  • @desc :数据源配置类 */ @Slf4j //表示这个类为一个配置类 @Configuration @MapperScan(basePackages = "com.lsh.mapper.db2", sqlSessionFactoryRef = "test2SqlSessionFactory") public class DataSourceConfig2 { @Bean(name = "test2DataSource") @ConfigurationProperties(prefix = "spring.datasource.db2") public DataSource getDateSource2() { return DataSourceBuilder.create().build(); } @Bean(name = "test2SqlSessionFactory") public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource datasource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(datasource); bean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("mybatis/mapper/db2/**.xml")); return bean.getObject(); } @Bean("test2SqlSessionTemplate") public SqlSessionTemplate test2sqlsessiontemplate( @Qualifier("test2SqlSessionFactory") SqlSessionFactory sessionfactory) { return new SqlSessionTemplate(sessionfactory); } public DataSourceConfig2(){ log.info("加载2数据源配置"); } }

分别在com.lsh.mapper包下新建db1和db2,用来放Mapper接口类。 image.png

在resource目录下新建mybatis/mapper/,新建db1和db2,用来存放Mapper.xml文件。 image.png

Bug 别名无效