博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot 之集成MyBatis
阅读量:2455 次
发布时间:2019-05-10

本文共 12948 字,大约阅读时间需要 43 分钟。

文章目录

数据源配置参考:https://blog.csdn.net/const_/article/details/96977428

准备数据库表。

CREATE TABLE `user`  (  `id` int(32) NOT NULL AUTO_INCREMENT,  `user_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,  `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,  `real_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,  PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 32 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;INSERT INTO `user` VALUES (2, 'tom', '123', 'tomjames');INSERT INTO `user` VALUES (3, 'James', '123456', 'LenJames');

导入依赖

mysql
mysql-connector-java
5.1.42
runtime
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
tk.mybatis
mapper-spring-boot-starter
2.0.2
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.5

MyBatis配置

1、application.yml

spring:  datasource:    driver-class-name: com.mysql.jdbc.Driver    url: jdbc:mysql://localhost:3306/test?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=true    username: root    password: 123456mybatis:  # mapper配置文件路径  mapper-locations: classpath:mapper/*Mapper.xml  # 配置实体类包路径  type-aliases-package: com.example.demo.entity  configuration:    # 开启自动驼峰    map-underscore-to-camel-case: true    # 设置生成的主键值会被回显到插入对象中    use-generated-keys: true# 通用Mappermapper:  # 设置以后,会去判断 insert 和 update 中符串类型!=’’  not-empty: true  # 枚举按简单类型处理,如果有枚举字段则需要加上该配置才会做映射  enum-as-simple-type: truelogging:  level:    # 打印sql语句    com.example.demo.mapper: debug

2、SpringBoot 启动类

@SpringBootApplication// 扫描mapper接口路径//如果使用通用Mapper,应该导入import tk.mybatis.spring.annotation.MapperScan这个包@MapperScan("com.example.demo.mapper")public class SpringbootStudyApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootStudyApplication.class, args); }}

3、UserMapper.java

@Mapperpublic interface UserMapper extends BaseMapper
{
User Sel(int id);}

4、UserMapper.xml

id, user_name, password, real_name
insert into t_user (id, user_name, password, real_name) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{realName,jdbcType=VARCHAR})

使用Java文件配置方式和Druid数据源

项目整体目录结构。

1、导入依赖

2、数据库信息配置

resources目录下创建 jdbc2.properties 配置文件。

jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8jdbc.username=rootjdbc.password=123456jdbc.initialSize=5jdbc.maxActive=5jdbc.maxIdle=5jdbc.minIdle=1jdbc.maxWait=6000jdbc.validationQuery=SELECT 1 FROM DUAL

3、数据源配置

实体类包路径修改成自己的实体类包路径。

import com.alibaba.druid.pool.DruidDataSource;import lombok.Getter;import lombok.Setter;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import javax.sql.DataSource;@Configuration@PropertySource(value = "classpath:jdbc2.properties")@ConfigurationProperties(prefix = "jdbc")@Getter@Setterpublic class DruidConfig {
private String url; private String username; private String password; private Integer initialSize; private Integer maxActive; private String maxIdle; private String minIdle; private Long maxWait; private String validationQuery; @Bean public DataSource druidDataSource() {
DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setInitialSize(initialSize); dataSource.setMaxActive(maxActive); dataSource.setMaxWait(maxWait); dataSource.setTimeBetweenEvictionRunsMillis(60000); dataSource.setMinEvictableIdleTimeMillis(300000); dataSource.setValidationQuery(validationQuery); dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setTestOnReturn(false); dataSource.setPoolPreparedStatements(true); return dataSource; } @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception{
SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setDataSource(druidDataSource()); // 每张表对应的xml文件 factory.setMapperLocations(resolver.getResources(("classpath:mapper/*Mapper.xml"))); // 每一张表对应的实体类 factory.setTypeAliasesPackage("com.example.Entity"); /* // mybatis配置文件的位置 // factory.setConfigLocation(resolver.getResource(("classpath:mybatis/mybatis-config.xml"))); */ org.apache.ibatis.session.Configuration configuration = factory.getObject().getConfiguration(); // 开启自动驼峰-下划线命名规则,默认false: Table(create_time) -> Entity(createTime) configuration.setMapUnderscoreToCamelCase(true); return factory.getObject(); }}

Mapper扫描包路径修改成自己的mapper接口包路径。

import org.mybatis.spring.mapper.MapperScannerConfigurer;import org.springframework.boot.autoconfigure.AutoConfigureAfter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration// 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解@AutoConfigureAfter(DruidConfig.class)public class MyBatisMapperScannerConfig {
@Bean public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer(); mapperScanner.setSqlSessionFactoryBeanName("sqlSessionFactory"); mapperScanner.setBasePackage("com.example.mapper"); return mapperScanner; }}

4、创建entity实体、mapper接口

通用Mapper采用了JPA规范包中的注解。
实体:

import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data@NoArgsConstructor@AllArgsConstructor@Table(name = "user")public class User {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String userName; private String passWord; private String realName;}

Mapper:

import com.example.demo.Entity.User;public interface UserMapper{
public User selectById(Long id); public Long insert(User user);}

5、编写Mapper配置文件

resources创建mapper文件夹,并创建UserMapper.xml配置文件。
namespace修改成自己对应的Mapper接口类全路径名。
配置文件中的实体类只写了实体类名,因为在配置数据源的时候,配置了实体类别名的包路径。

insert into user (user_name, password, real_name) values (#{userName}, #{passWord}, #{realName})

6、编写控制器

import com.example.mapper.UserMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping("/")public class UserController {
@Autowired UserMapper userMapper; @GetMapping("/user") @ResponseBody public String demo() {
return userMapper.selectById(2L).toString(); }}

8、访问测试

在这里插入图片描述

MyBatis多数据源

导入依赖

org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.0
com.alibaba
druid-spring-boot-starter
1.1.17
mysql
mysql-connector-java
5.1.28
runtime

多数据源application.properties中的配置

spring.datasource.one.url=jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8spring.datasource.one.username=rootspring.datasource.one.password=123456spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.two.url=jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8spring.datasource.two.username=rootspring.datasource.two.password=123456spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource

提供两个DataSource

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;@Configurationpublic class DataSourceConfig {
@Bean @ConfigurationProperties(prefix = "spring.datasource.one") DataSource dsOne() {
return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.two") DataSource dsTwo() {
return DruidDataSourceBuilder.create().build(); }}

MyBatis配置(两个数据源在两个类中分开来配置)

第一个数据源配置

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.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import javax.annotation.Resource;import javax.sql.DataSource;@Configuration@MapperScan(basePackages = "com.demo.mapper1",        sqlSessionFactoryRef = "sqlSessionFactory1",        sqlSessionTemplateRef = "sqlSessionTemplate1")public class MyBatisConfigOne {
@Resource(name = "dsOne") DataSource dsOne; @Bean SqlSessionFactory sqlSessionFactory1() {
SqlSessionFactory sessionFactory = null; try {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setDataSource(dsOne); // 每张表对应的xml文件 bean.setMapperLocations(resolver.getResources(("classpath:mapper/*Mapper.xml"))); // 每一张表对应的实体类 bean.setTypeAliasesPackage("com.demo.entity"); sessionFactory = bean.getObject(); } catch (Exception e) {
e.printStackTrace(); } return sessionFactory; } @Bean SqlSessionTemplate sqlSessionTemplate1() {
return new SqlSessionTemplate(sqlSessionFactory1()); }}

第二个数据源配置

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.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import javax.annotation.Resource;import javax.sql.DataSource;@Configuration@MapperScan(basePackages = "com.demo.mapper2",        sqlSessionFactoryRef = "sqlSessionFactory2",        sqlSessionTemplateRef = "sqlSessionTemplate2")public class MyBatisConfigTwo {
@Resource(name = "dsTwo") DataSource dsTwo; @Bean SqlSessionFactory sqlSessionFactory2() {
SqlSessionFactory sessionFactory = null; try {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setDataSource(dsTwo); // 每张表对应的xml文件 bean.setMapperLocations(resolver.getResources(("classpath:mapper/*Mapper.xml"))); // 每一张表对应的实体类 bean.setTypeAliasesPackage("com.demo.entity"); sessionFactory = bean.getObject(); } catch (Exception e) {
e.printStackTrace(); } return sessionFactory; } @Bean SqlSessionTemplate sqlSessionTemplate2() {
return new SqlSessionTemplate(sqlSessionFactory2()); }}

mapper和实体类创建

@Datapublic class User {
private int id; private String name;}public interface UserMapperOne {
List
getAllUser();}public interface UserMapperTwo {
List
getAllUser();}

mapper对应的XML配置

最后,在Service中注入两个不同的Mapper,不同的Mapper将操作不同的数据源。

参考:

你可能感兴趣的文章
Python字符串| join()方法与示例
查看>>
C ++ STL中的set :: upper_bound()函数
查看>>
Java Collections list()方法与示例
查看>>
strictmath_Java StrictMath log1p()方法与示例
查看>>
treeset java_Java TreeSet pollLast()方法与示例
查看>>
scala字符替换_如何替换Scala中的“坏”字符?
查看>>
python 温度转换程序_Python程序将米转换为码
查看>>
图形学 射线相交算法_计算机图形学中的阴极射线管
查看>>
操作系统多线程实现_操作系统中的线程实现
查看>>
坐标转换 计算机图形学_计算机图形学的转换类型
查看>>
scala中命名参数函数_Scala中带有命名参数的函数
查看>>
c ++查找字符串_C ++数组| 查找输出程序| 套装5
查看>>
linux下g++和gcc_Linux中gcc和g ++有什么区别?
查看>>
c语言中图形驱动程序功能_C / C ++中的图形:一些更有趣的功能
查看>>
stl vector 函数_vector :: crend()函数以及C ++ STL中的示例
查看>>
acquire方法_Python锁类| 带有示例的acquire()方法
查看>>
Python字符串| 带示例的format()方法
查看>>
float.equals_Java Float类equals()方法与示例
查看>>
Java Hashtable hashCode()方法及示例
查看>>
python 示例_带有示例的Python date isocalendar()方法
查看>>