支付项目:3、MyBatis 三剑客

MyBatis VS Jpa

Jpa 是趋势!!

MyBatis 是现状!!

MyBatis 注解使用(了解)

1、添加依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

2、在 application.yml 中添加配置文件

spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/mall?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC

3、创建实体类(省略 get 和 set 方法)

package com.xiaoxin.mall_pay.pojo;

import java.util.Date;

public class Category {

    private Integer id;

    private Integer parentId;

    private String name;

    private Integer status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;

    @Override
    public String toString() {
        return "Category{" +
                "id=" + id +
                ", parentId=" + parentId +
                ", name='" + name + '\'' +
                ", status=" + status +
                ", sortOrder=" + sortOrder +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                '}';
    }
}

4、创建 mapper 接口

package com.xiaoxin.mall_pay.dao;

import com.xiaoxin.mall_pay.pojo.Category;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface CategoryMapper {

    @Select("select * from mall_category where id=#{id}")
    Category findById(@Param("id") Integer id);
}

5、运行

package com.xiaoxin.mall_pay;


import com.xiaoxin.mall_pay.dao.CategoryMapper;
import com.xiaoxin.mall_pay.pojo.Category;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MallPayApplicationTests {

    @Autowired
    private CategoryMapper categoryMapper;

    @Test
    public void contextLoads() {
        Category category = categoryMapper.findById(100001);
        System.out.println(category);
    }
}

① 输出的时候出现问题:
在这里插入图片描述
parentId 还有一些其它的元素为 null,这是由于表中是按下划线来命名的,但是实体类是用驼峰来命名的,因为不匹配所以导致没查到这些元素。解决办法是在 application.yml 中进行配置:

spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/mall?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC

mybatis:
    configuration:
        map-underscore-to-camel-case: true

最后的输出结果就是正确的了!!
在这里插入图片描述
② 每个mapper接口上面都要写一个 @Mapper 注解,太麻烦,在 MallPayApplication 类(启动主类)上添加一个 mapper-scan 注解可解决这个问题:

package com.xiaoxin.mall_pay;

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

@SpringBootApplication
@MapperScan(basePackages = "com.xiaoxin.mall_pay.dao")
public class MallPayApplication {

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

③ 设置自动导包。设置中输入 import,然后勾选上红色框内的选项。

这样的话,当所需包只有一个选项时,会帮我们自动导入。
在这里插入图片描述
④ lombok 插件

每次写实体类时,都要写 get 、set 和 toString 方法,而 lombok 可以帮我们都实现,只需要加一个注解即可。

添加 lombok 的依赖:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

在插件市场中查找并安装 lombok 插件:
在这里插入图片描述
在实体类上添加@Data注解:

package com.xiaoxin.mall_pay.pojo;

import lombok.Data;

import java.util.Date;

@Data
public class Category {

    private Integer id;

    private Integer parentId;

    private String name;

    private Integer status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;
}

MyBatis Xml 使用(熟练掌握)

1、在 resources 下新建目录 mappers,添加文件 CategoryMapper.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.xiaoxin.mall_pay.dao.CategoryMapper">
    <select id="queryById" resultType="com.xiaoxin.mall_pay.pojo.Category">
        select * from mall_category where id = #{id}
    </select>
</mapper>

2、在 application.yml 中配置 CategoryMapper.xml:

spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/mall?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC

mybatis:
    configuration:
        map-underscore-to-camel-case: true
    mapper-locations: classpath:mappers/*.xml

3、编写测试代码:

package com.xiaoxin.mall_pay;


import com.xiaoxin.mall_pay.dao.CategoryMapper;
import com.xiaoxin.mall_pay.pojo.Category;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MallPayApplicationTests {

    @Autowired
    private CategoryMapper categoryMapper;

    @Test
    public void contextLoads() {
        Category category = categoryMapper.findById(100001);
        System.out.println(category);
    }

    @Test
    public void queryByIdTest() {
        Category category = categoryMapper.queryById(100001);
        System.out.println(category);
    }
}

4、对 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.xiaoxin.mall_pay.dao.CategoryMapper">

    <sql id="Base_Colume_List">
        id, parent_id, `name`, status, sort_order, create_time, update_time
    </sql>

    <select id="queryById" resultType="com.xiaoxin.mall_pay.pojo.Category">
        select <include refid="Base_Colume_List"/>
        from mall_category
        where id = #{id}
    </select>
</mapper>

5、一般为每个mapper专门写一个测试文件。在CategoryMapper文件中,右键 go to,选择Test,在提示中选择create test。
然后再编写测试类:

package com.xiaoxin.mall_pay.dao;

import com.xiaoxin.mall_pay.MallPayApplicationTests;
import com.xiaoxin.mall_pay.pojo.Category;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class CategoryMapperTest extends MallPayApplicationTests {

    @Autowired
    private CategoryMapper categoryMapper;

    @Test
    public void findById() {
    }

    @Test
    public void queryById() {
        Category category = categoryMapper.queryById(100001);
        System.out.println(category);
    }

这里继承MallPayApplicationTests 类的原因是可以不用写类上面的@SpringBootTest、@RunWith(SpringRunner.class)这两个注解

MyBatis 三剑客

  • MyBatis-generator:用来自动生成实体类、mapper、xml文件
  • free-MyBatis-plugin:mapper类中的方法 跳转到 xml中相应的标签
  • MyBatis-PageHelper:用来分页

1、MyBatis-generator

① 添加依赖和插件

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.5</version>
</dependency>

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

② 编写配置文件 generatorConfig.xml

<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!-- 配置mysql驱动的jar包 -->
    <classPathEntry location="D:\Java\apache-maven-3.6.3\maven-repo\mysql\mysql-connector-java\5.0.4\mysql-connector-java-5.0.4.jar"/>

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

        <!-- 配置数据库连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mall?characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=UTC"
                        userId="root"
                        password="123456"/>

        <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 用于生成实体类 -->
        <javaModelGenerator targetPackage="com.xiaoxin.mall_pay.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 用于生成mapper.xml文件 -->
        <sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 用于生成mapper接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xiaoxin.mall_pay.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <table tableName="mall_order" domainObjectName="Order"/>
    </context>
    
</generatorConfiguration>

③ 执行命令:mvn mybatis-generator:generate
在这里插入图片描述
④ 再次执行generate命令,发现并没有覆盖前面执行的,解决方法:在插件中增加配置

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

⑤ 注释实在太多,在jdbcConnection标签的前面添加commentGenerator:

<commentGenerator>
    <property name="suppressAllComments" value="true"/>
</commentGenerator>

<!-- 配置数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/mall?characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=UTC"
                userId="root"
                password="123456"/>

⑥ 不想要OrderExample 类:

<!-- 配置表的名字以及类的名字 -->
<table tableName="mall_order" domainObjectName="Order" 
       enableUpdateByExample="false" enableSelectByExample="false"
        enableDeleteByExample="false" enableCountByExample="false"/>

⑦ 每次 generate 的时候,都会在 xml 后面追加内容,解决方法,使用UnmergeableXmlMappersPlugin插件。plugin 标签要写在 commentGenerator 标签之前

<!-- 不再追加xml内容 -->
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>

<commentGenerator>
    <property name="suppressAllComments" value="true"/>
</commentGenerator>

⑧ 编写测试类,运行成功!

package com.xiaoxin.mall_pay.dao;

import com.xiaoxin.mall_pay.MallPayApplicationTests;
import com.xiaoxin.mall_pay.pojo.Category;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class CategoryMapperTest extends MallPayApplicationTests {

    @Autowired
    private CategoryMapper categoryMapper;

    @Test
    public void deleteByPrimaryKey() {
    }

    @Test
    public void insert() {
    }

    @Test
    public void insertSelective() {
    }

    @Test
    public void selectByPrimaryKey() {
        Category category = categoryMapper.selectByPrimaryKey(100001);
        System.out.println(category);
    }

    @Test
    public void updateByPrimaryKeySelective() {
    }

    @Test
    public void updateByPrimaryKey() {
    }
}

2、Free-MyBatis-plugin
在这里插入图片描述
3、MyBatis-PageHelper

后面有需要分页的地方再来讲解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值