栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

Springboot 系列(十一)使用 Mybatis(自动生成插件) 访问数据库

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot 系列(十一)使用 Mybatis(自动生成插件) 访问数据库

1. Springboot mybatis 介绍

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数获取结果集的过程。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

关于 Mybatis 的基础知识可以查询官方文档,十分的详细。mybatis 官方文档.

2. Springboot mybatis 依赖

本系列 Springboot 文章主要是 Springboot 的学习与分析,也因此只会试验 Mybatis 在 Springboot 中的一些用法,关于 Mybatis 的基础知识,还是需要自行学习的。
创建 Springboot 项目不提,引入 maven 依赖,主要是 mybastis 核心依赖以及一个 mybatis xml 自动生成插件。依赖中的 druid 数据源部分,可以参考系列文章第九篇。

 
        
        
            org.springframework.boot
            spring-boot-starter-web
            
                
                    spring-boot-starter-json
                    org.springframework.boot
                
            
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            com.alibaba
            fastjson
            1.2.47
        

        
        
            org.projectlombok
            lombok
            true
        

        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        

        
        
            org.junit.jupiter
            junit-jupiter-api
            RELEASE
            compile
        

        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        
        
        
            org.mybatis.generator
            mybatis-generator-core
            1.3.7
            compile
            true
        

        
        
            mysql
            mysql-connector-java
        
    
3. Springboot mybatis 配置

关于 Druid 数据源的配置不再说明,可以参考系列文章第九篇。配置中主要配置了项目编码、数据源信息、durid 数据源和 mybatis 的 mapper 位置以及 mybatis 映射别名的包路径。

############################################################# 服务启动端口号server.port=8080
spring.profiles.active=dev# 编码server.tomcat.uri-encoding=utf-8
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true############################################################spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot?characterEncoding=utf-8&serverTimezone=GMT%2B8spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123# 使用 druid 数据源spring.datasource.type: com.alibaba.druid.pool.DruidDataSourcespring.datasource.initialSize: 5spring.datasource.minIdle: 5spring.datasource.maxActive: 20spring.datasource.maxWait: 60000spring.datasource.timeBetweenEvictionRunsMillis: 60000spring.datasource.minEvictableIdleTimeMillis: 300000spring.datasource.validationQuery: SELECt 1 FROM DUALspring.datasource.testWhileIdle: truespring.datasource.testOnBorrow: falsespring.datasource.testOnReturn: falsespring.datasource.poolPreparedStatements: truespring.datasource.filters: statspring.datasource.maxPoolPreparedStatementPerConnectionSize: 20spring.datasource.useGlobalDataSourceStat: truespring.datasource.connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500# mybatismybatis.mapper-locations=classpath:mapperpublic class MybatisGenerator {    public void generator() throws Exception {
        ArrayList warnings = new ArrayList<>();        boolean overwrite = true;        // 指定你想工程配置文件
        File configFile = new File("generatorConfig.xml");
        System.out.println(configFile.getAbsolutePath());
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }    public static void main(String[] args) throws Exception {
        MybatisGenerator mybatisGenerator = new MybatisGenerator();
        mybatisGenerator.generator();
    }
}

生成的文件如下图。



查看生成的接口以及 XML 映射文件可以发现已经自动生成了常用的几个方法。

  1. deleteByPrimaryKey

  2. insert

  3. updateByPrimaryKey

  4. selectByPrimaryKey

  5. selectAll

生成完成之后要在 Springboot 启动器上添加 MapperScan 注解指定要扫描的 mapper 位置。

@SpringBootApplication@MapperScan("net.codingme.boot.domain.mapper")public class BootApplication {    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class, args);
    }
}
4.3. 注解配置方式

Mybatis 同样支持注解的方式配置映射关系,使用注解可以替代 XML 的配置,写一个简单的注解例子。在刚才生成的 BookMapper.java 中增加一个根据作者名称查询的方法,并映射字段对应的属性。

// 添加 @Repository 注解,这样在使用 @Autowired 引入的时候不会报横线@Repositorypublic interface BookMapper {     
    @Results({            @Result(property = "id", column = "ids"),            @Result(property = "name", column = "name"),            @Result(property = "author", column = "authors"),            @Result(property = "createTime", column = "create_time")
    })    @Select("select id as ids, author as authors, name, price, create_time, description from book where author = #{author}")    List selectByAuthor(@Param("author") String author);    // 省略下面自动生成代码
5. Springboot mybatis 测试

正常情况下会在项目中的业务层 service 包下创建接口和类然后通过注解引入使用。

@Autowiredprivate BookMapper bookMapper;

我们只是实验,没有这样写一套的必要,只要能确保 BookMapper 可以正常注入使用就好了。因此创建测试类进行测试。

在生成的(也可以完全手写测试方法)测试类中添加测试方法进行测试。

@RunWith(SpringRunner.class)@SpringBootTestpublic class BookMapperTest {    @Autowired
    private BookMapper bookMapper;    @Test
    public void testSelectAll() {
        List bookList = bookMapper.selectAll();
        Assert.assertNotNull(bookList);
        bookList.forEach((book) -> System.out.println(book));
    }    @Test
    public void testSelectByAuthro() {
        List bookList = bookMapper.selectByAuthor("金庸");
        Assert.assertNotNull(bookList);
        bookList.forEach((book) -> System.out.println(book));
    }    @Test
    public void testSelectByPrimaryKey() {
        Book book = bookMapper.selectByPrimaryKey(2);
        Assert.assertNotNull(book);
        System.out.println(book);
    }    public void testDeleteByPrimaryKey() {        int primaryKey = bookMapper.deleteByPrimaryKey(8);
        Assert.assertNotEquals(0, primaryKey);
        System.out.println(primaryKey);
    }
    
}

为了观察查询接口 book 的信息输出,重写 Book 类的 toString 方法,然后运行单元测试。

可以发现测试全部通过。结果正常。
文章代码已经上传到 Github Spring Boot 连接数据库 - Mybatis。

作者:雪漫士兵

原文出处:https://www.cnblogs.com/niumoo/p/10488414.html  

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235060.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号