美文网首页
spring-boot集成mybatis三剑客

spring-boot集成mybatis三剑客

作者: 梁某人的剑 | 来源:发表于2020-06-11 16:51 被阅读0次

Mybatis与Jpa的选择

Jpa的使用非常简洁,开发效率非常高,国际范围内有更多人支持。
但是在中国,有很多人使用Mybatis。

SpringBoot整合Mybatis

安装依赖

文档

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
dependencies {
  compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3")
}

项目配置

# 配置数据库与数据库连接驱动
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/MoocMall?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: pass
    driver-class-name: com.mysql.jdbc.Driver

通过注解的方式使用Mybatis

public class Category {
    private Integer id;

    private Integer parentId;

    private String name;

    private Boolean status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;
}
@Mapper
public interface CategoryMapper {
    @Select("select * from category where id = #{id}")
    Category selectByPrimaryKey(Integer id);
}

通过配置,测试categoryMapper.selectByPrimaryKey("xxxx")的返回值中部分字段(parentId、sortOrder、createTime、updateTime)值为null,这是因为POJO与数据库的映射没有匹配。可以通过配置mybatis的map-underscore-to-camel-case为ture解决。

spring:
  ...
mybatis:
  configuration:
    map-underscore-to-camel-case: true
    # 控制台日志配置
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Mybatis的mapper组件需要添加@Mapper注解才能被Spring识别,为了方便可以统一在Application的main函数添加mapper包的自动扫描:

@SpringBootApplication
@MapperScan(basePackages = "com.imooc.mall.entities.dao")
public class MallApplication {

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

}

IDEA的配置

自动刷新Maven & Gradle依赖

  • Build,Excution,Deployment->Build Toold->Maven->Importing
    • Build,Excution,Deployment->Build Toold->Gradle

自动倒包

  • 手动导入:Option + Enter
  • 配置自动:Editor->General->Auto Import

通过XML配置使用Mybatis

public interface CategoryMapper {
    Category selectByPrimaryKey(Integer id);
}

指定XML文件扫描路径

# application.yml
spring:
  ...
mybatis:
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 配置XML文件的扫描路径
  mapper-locations: classpath:mappers/*.xml

手写Mybatis XML:
查看文档,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.xx.xxx.entities.dao.CategoryMapper">
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultType="com.xx.xxx.entities.Category">
    select * from category
    where id = #{id,jdbcType=INTEGER}
  </select>
</mapper>

不建议使用select * ...:

<!--声明-->
<?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.xx.xxx.entities.dao.CategoryMapper">
  <sql id="Base_Column_List">
    id, parent_id, name, status, sort_order, create_time, update_time
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultType="com.xx.xxx.entities.Category">
    select
    <include refid="Base_Column_List" />
    from mall_category
    where id = #{id,jdbcType=INTEGER}
  </select>
</mapper>

mybatis-generator

生成器的原理:连接数据库 -> 获取表结构 -> 生成文件

安装依赖

文档

<plugin>
  <groupId>org.mybatis.generator</groupId>
  <artifactId>mybatis-generator-maven-plugin</artifactId>
  <version>1.4.0</version>
</plugin>

执行命令:mvn mybatis-generator:generate

添加配置文件:src/main/resources/generatorConfig.xml
配置文件内容模板,见文档
配置详解:见博客

例子:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--配置connector的绝对路径-->
    <classPathEntry location="/Users/lrliang/Desktop/mysql-connector-java-5.1.6.jar" />

    <context id="DB2Tables" targetRuntime="MyBatis3">

        <!--多次生成XML文件时,覆盖文件,而不是追加xml内容-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />

        <!--去掉生成文件中的注释-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库连接配置-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/Mall?characterEncoding=utf-8"
                        userId="root"
                        password="pass">
        </jdbcConnection>

        <!--设置为false,区分Integer,Long,BigDecimals-->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--配置生成的Entity文件的路径-->
        <javaModelGenerator targetPackage="com.xx.xxx.entities" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--生成Mybatis XML文件存放的路径-->
        <sqlMapGenerator targetPackage="mappers"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!--生成src下的MapperBean文件路径-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xx.xxx.entities.dao"  targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--数据库表配置-->
        <table tableName="order" domainObjectName="Order" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
    </context>
</generatorConfiguration>

配置重复生成的文件覆盖原先生成的文件

<plugin>
   <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.7</version>

    <configuration>
        <overwrite>true</overwrite>
    </configuration>
</plugin>

生成的文件

Category

public class Category {
    private Integer id;

    private Integer parentId;

    private String name;

    private Boolean status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;

    //getter & setter(可以手动删除,使用Lombok @Data注解)
    ...
}

CategoryMapper

public interface CategoryMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Category record);

    int insertSelective(Category record);

    Category selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Category record);

    int updateByPrimaryKey(Category record);

    List<Category> selectAll();
}

Mybatis Plugin: 在IDE中将Mapper文件与XML文件关联起来

Mybatis Plugin已经开始收费,可以使用替代版:Free-Mybatis-plugin

Mybatis PageHelper:Mybatis通用分页插件

国人开发、开源的Mybatis通用分页插件:文档及源代码

安装依赖:

<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>1.2.4</version>
</dependency>
<!--pagehelper-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>

使用案例:

    @Override
    public ResponseVo<PageInfo> list(Integer categoryId, Integer pageNum, Integer pageSize) {
        Set<Integer> categoryIds = new HashSet<>();
        if (categoryId != null) {
            categoryIds = categoryService.findSubCategoryIds(categoryId);
            categoryIds.add(categoryId);
        }

        // 只需要在需要分页的地方加上PageHelper.startPage
        PageHelper.startPage(pageNum, pageSize);
        final List<Product> productList = productMapper.selectByCategoryIdSet(categoryIds);
        List<ProductVo> productVoList = productList
                .stream()
                .map(this::product2ProductVo)
                .collect(Collectors.toList());

        PageInfo pageInfo = new PageInfo<>(productVoList);
        pageInfo.setList(productVoList);
        return ResponseVo.success(pageInfo);
    }

相关文章

网友评论

      本文标题:spring-boot集成mybatis三剑客

      本文链接:https://www.haomeiwen.com/subject/wyobtktx.html