(2-10-1)MyBatis的基础与基本使用

目录

0.前置小节

[1. MyBatis 框架介绍](#1. MyBatis 框架介绍)

[1.1 软件开发中的框架](#1.1 软件开发中的框架)

[1.2 使用框架的好处](#1.2 使用框架的好处)

[1.3 SSM 开发框架](#1.3 SSM 开发框架)

[1.4 什么是 MyBatis](#1.4 什么是 MyBatis)

[1.5 MyBatis 的开发流程](#1.5 MyBatis 的开发流程)

[2. MyBatis 的开发流程](#2. MyBatis 的开发流程)

[2.0 MyBatis的工作流程](#2.0 MyBatis的工作流程)

[2.1 引入 MyBatis 依赖](#2.1 引入 MyBatis 依赖)

00.base(目录、pom、单元测试、Junit4)

01.Calculator

[02. CalculatorTest](#02. CalculatorTest)

[2.2 创建核心配置文件](#2.2 创建核心配置文件)

[00. mybatis-config.xml](#00. mybatis-config.xml)

[01. 引入myBatis 与Mysql-jdbc 依赖](#01. 引入myBatis 与Mysql-jdbc 依赖)

[02. 添加 Mysql 数据源](#02. 添加 Mysql 数据源)

[03. 测试连接](#03. 测试连接)

[04. 导入sql脚本](#04. 导入sql脚本)

[05. 编写 mybatis-config.xml](#05. 编写 mybatis-config.xml)

06.单元测试(sqlSession)

[07. 创建工具类 MyBatisUtils](#07. 创建工具类 MyBatisUtils)

[2.3 Mybatis 数据查询步骤](#2.3 Mybatis 数据查询步骤)

[01. 编写Goods实体类](#01. 编写Goods实体类)

[02. 创建 Mapper 文件](#02. 创建 Mapper 文件)

[03. 编写select SQL 标签](#03. 编写select SQL 标签)

[04. 开启驼峰命名映射](#04. 开启驼峰命名映射)

[05. 新增mapper](#05. 新增mapper)

[06. SqlSession执行select语句](#06. SqlSession执行select语句)

[07. SQL 传单参](#07. SQL 传单参)

[08. SQL 传多参](#08. SQL 传多参)

[3. 结果集映射查询](#3. 结果集映射查询)

[3.1 利用 LinkedHashMap 保存多表关联结果](#3.1 利用 LinkedHashMap 保存多表关联结果)

00.base

[01. goods.xml](#01. goods.xml)

[02. testSelectGoodsMap()](#02. testSelectGoodsMap())

[03. 实现效果](#03. 实现效果)

[3.2 ResultMap 结果映射](#3.2 ResultMap 结果映射)

[01. 新建dto 数据传输对象](#01. 新建dto 数据传输对象)

[02. 编写测试类](#02. 编写测试类)

[03. 运行效果](#03. 运行效果)

[3.3 ResultMap 进一步的封装](#3.3 ResultMap 进一步的封装)

[01. Category](#01. Category)

[02. 完善GoodsDTO](#02. 完善GoodsDTO)

[03. goods.xml](#03. goods.xml)

[04. 运行效果](#04. 运行效果)

[4. 数据插入](#4. 数据插入)

[4.1数据库事务 与 insertDemo](#4.1数据库事务 与 insertDemo)

[4.2 goods.xml](#4.2 goods.xml)

4.3.testInsertGoods()

[4.4 新增Id无法获取](#4.4 新增Id无法获取)

[4.5 selectKey完善good.xml](#4.5 selectKey完善good.xml)

[4.5 useGeneratedKeys完善good.xml](#4.5 useGeneratedKeys完善good.xml)

[4.6 selectKey与useGeneratedKeys的区别](#4.6 selectKey与useGeneratedKeys的区别)

[5. 更新数据](#5. 更新数据)

[5.1 baseDemo](#5.1 baseDemo)

[5.2 goods.xml](#5.2 goods.xml)

[5.3 testUpdateGoods()](#5.3 testUpdateGoods())

[6. 删除数据](#6. 删除数据)

[6.1 baseDemo](#6.1 baseDemo)

[6.2 goods.xml](#6.2 goods.xml)

[6.3 deleteUpdateGoods()](#6.3 deleteUpdateGoods())

[7. Mybatis 预防SQL注入攻击](#7. Mybatis 预防SQL注入攻击)

[7.1 baseDemo](#7.1 baseDemo)

[7.2 MyBatis 的两种传值方式](#7.2 MyBatis 的两种传值方式)

[7.3 goods.xml](#7.3 goods.xml)

7.4 testSelectByTitle01(#{})

[7.5 testSelectByTitle02()](#7.5 testSelectByTitle02())


官方文档网站:

MyBatis 中文网 官网

0.前置小节

1. MyBatis 框架介绍

1.1 软件开发中的框架

1.2 使用框架的好处

1.3 SSM 开发框架

1.4 什么是 MyBatis

1.5 MyBatis 的开发流程

2. MyBatis 的开发流程

2.0 MyBatis的工作流程

2.1 引入 MyBatis 依赖

00.base(目录、pom、单元测试、Junit4)
XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.phdvb</groupId>
    <artifactId>MyBatisProj</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
        <!--配置阿里云私服远程仓库,  当阿里云的私服没有的时候才回去官网下载-->
    <repositories>
        <repository>
            <id>aliyun</id>
            <name>aliyun</name>
            <url>https://maven.aliyun.com/repository/public</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>
01.Calculator
java 复制代码
package com.phdvb.junit;

public class Calculator {
    //加法运算
    public int add(int a, int b) {
        return a + b;
    }

    //减法运算
    public int substruct(int a, int b) {
        return a - b;
    }

    //乘法运算
    public int multiply(int a, int b) {
        return a * b;
    }

    //除法运算
    public int divide(int a, int b) {
        return a / b;
    }
}
02. CalculatorTest
java 复制代码
import com.phdvb.junit.Calculator;
import org.junit.Test;

public class CalculatorTest {
    private Calculator calculator = new Calculator();
    @Test
    public void test(){
        System.out.println(calculator.add(1, 2));
        System.out.println(calculator.substruct(1,2));
        System.out.println(calculator.multiply(1,2));
        System.out.println(calculator.divide(1,2));
    }
}

2.2 创建核心配置文件

00. mybatis-config.xml

参考demo:

01. 引入myBatis 与Mysql-jdbc 依赖
02. 添加 Mysql 数据源
03. 测试连接
04. 导入sql脚本

通过网盘分享的文件:(10.1.3)--MyBatis源代码【 全网最全it资源v:it1646】.zip

链接: https://pan.baidu.com/s/1bSao39sgwziDwHtic91bsA 提取码: 7cqp 复制这段内容后打开百度网盘手机App,操作更方便哦

05. 编写 mybatis-config.xml
XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 设置默认指向的数据库-->
    <environments default="dev">
    <!-- 配置环境, 不同的环境对应不同的id名字-->
        <environment id="dev">
            <!-- 采用JDBC的方式对 数据库事务进行 commit/ rollback-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 采用连接池的方式管理数据库连接-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3303/phdvb?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
        <environment id="prod">
            <!-- 采用JDBC的方式对 数据库事务进行 commit/ rollback-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 采用连接池的方式管理数据库连接-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://114.114.114.114:3303/phdvb?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
06.单元测试(sqlSession)
java 复制代码
package com.phdvb.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

/**
 * Junit 单元测试 MyBatis
 */
public class MyBatisTestor {
    @Test
    public void testSqlSessionFactory() throws IOException {
        // 通过 Reader 加载classPath 下的 mybatis-config.xml 核心配置文件
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        // 初始化sqlSessionFactory对象, 同时解析下的 mybatis-config.xml 核心配置文件
        SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader);
        System.out.println("sqlSessionFactory加载成功!");
        SqlSession sqlSession = null;
        try{
            // 创建 SqlSession 对象,SqlSession 是JDBC 的扩展类, 用于与数据库交互
            sqlSession = sqlSessionFactory.openSession();
            // 创建数据库连接(测试使用,正常情况下不需要手动创建)
            Connection connection = sqlSession.getConnection();
            System.out.println(connection);      //com.mysql.cj.jdbc.ConnectionImpl@2d127a61
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if(sqlSession != null){
                // 如果 type = "POOLED", 代表使用的是连接池,close()则是将连接回收到连接池中
                // 如果 type = "UNPOOLED", 代表的是直连, close()则会条用Connection.close()关闭连接
                sqlSession.close();
            }
        }
    }
}
07. 创建工具类 MyBatisUtils
java 复制代码
package com.phdvb.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * 将 MyBatisTestor 的i相关 方法 ,封装为工具类
 */
public class MyBatisUtils {
    // 利用 static(静态) 属于类不属于对象, 且全局唯一
    private static SqlSessionFactory sqlSessionFactory = null;

    // 利用静态块 在初始化时 实例化sqkSessionFactory
    static{
        Reader reader = null;
        try {
            // 通过 Reader 加载classPath 下的 mybatis-config.xml 核心配置文件
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            // 对sqlSessionFactory对象赋值, 同时解析下的 mybatis-config.xml 核心配置文件
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            // 初始化错误时, 通过抛出异常 ExceptionInInitializerError 通知调用者
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * 创建一个 新的SqlSession 对象
     * @return
     */
    public static SqlSession openSession(){
        return sqlSessionFactory.openSession();
    }

    /**
     * 释放一个有效的 SqlSession  对象
     * @param session
     */
    public static void closeSession(SqlSession session){
        if(session != null){
            session.close();
        }
    }
}

单元测试方法:

java 复制代码
// 测试封装的MyBatisUtils工具类
    @Test
    public void testMybatisUtils(){
        SqlSession  sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            Connection connection = sqlSession.getConnection();
            System.out.println(connection);
        }catch (Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }

2.3 Mybatis 数据查询步骤

01. 编写Goods实体类
java 复制代码
package com.phdvb.mybatis.entity;

public class Goods {
    private Integer goodsId;            // 商品编号
    private String title;               // 商品标题
    private String subTitle;            // 子标题
    private Float originalCost;         // 原始价格
    private Float currentPrice;         // 当前价格
    private Float discount;             // 折扣率
    private Integer isFreeDelivery;     // 是否包邮(1-包邮, 0- 不包邮)
    private Integer categoryId;         // 分类编号

    public Integer getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(Integer goodsId) {
        this.goodsId = goodsId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

    public Float getOriginalCost() {
        return originalCost;
    }

    public void setOriginalCost(Float originalCost) {
        this.originalCost = originalCost;
    }

    public Float getCurrentPrice() {
        return currentPrice;
    }

    public void setCurrentPrice(Float currentPrice) {
        this.currentPrice = currentPrice;
    }

    public Float getDiscount() {
        return discount;
    }

    public void setDiscount(Float discount) {
        this.discount = discount;
    }

    public Integer getIsFreeDelivery() {
        return isFreeDelivery;
    }

    public void setIsFreeDelivery(Integer isFreeDelivery) {
        this.isFreeDelivery = isFreeDelivery;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }
}
02. 创建 Mapper 文件
03. 编写select SQL 标签
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="goods">
    <select id="selectAll" resultType="com.phdvb.mybatis.entity.Goods">
        select * from t_goods order by goods_id desc limit 7;
    </select>
</mapper>
04. 开启驼峰命名映射
05. 新增mapper
06. SqlSession执行select语句
sql 复制代码
@Test
    public void testSelectAll() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            List<Goods> list = sqlSession.selectList("goods.selectAll");
            for(Goods goods : list){
                System.out.println(goods.getGoodsId() + "-"+ goods.getTitle());
            }
        }catch (Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }
07. SQL 传单参

base:

goods.xml

XML 复制代码
    <!--SQL 传参 id-->
    <select id = "selectById" parameterType="Integer" resultType="com.phdvb.mybatis.entity.Goods">
        select * from t_goods where goods_id = #{value};
    </select>

测试方法

java 复制代码
    @Test
    public void testSelectById() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            Goods goods = sqlSession.selectOne("goods.selectById", 831);
            System.out.println(goods.getTitle());
        }catch (Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }

实现效果:

08. SQL 传多参

goods.xml

XML 复制代码
    <!--多参数传递-->
    <select id="selectByPriceRange" parameterType="java.util.Map" resultType="com.phdvb.mybatis.entity.Goods">
        select * from t_goods
        where
            current_price between #{minPrice} and #{maxPrice}
        limit 0, #{limitNum}
    </select>
复制代码
testSelectById
java 复制代码
    @Test
    public void selectByPriceRange() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            Map param = new HashMap();
            param.put("minPrice", 240);
            param.put("maxPrice", 740);
            param.put("limitNum", 5);
            List<Goods> list = sqlSession.selectList("goods.selectByPriceRange", param);
            for(Goods g: list){
                System.out.println(g.getGoodsId() + "-"+ g.getTitle()+'-'+g.getCurrentPrice());
            }
        }catch (Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }

实现效果:

3. 结果集映射查询

3.1 利用 LinkedHashMap 保存多表关联结果

00.base
复制代码
<!--利用 LinkedHashMap 保存多表关联结果-->
<!--
    1. Mybatis 会将每一条记录 包装为 LinkedHashMap对象
    2. 其中字段类型根据表结构自动判断
    3. 优点: 易于扩展,易用使用
    4. 缺点: 过于灵活, 无法进行编译时检查
-->
01. goods.xml
XML 复制代码
<!--利用 LinkedHashMap 保存多表关联结果-->
    <!--
        1.Mybatis 会将每一条记录 包装为 LinkedHashMap对象
        2.其中字段类型根据表结构自动判断
        3. 优点: 易于扩展,易用使用
        4. 缺点: 过于灵活, 无法进行编译时检查
    -->
    <select id="selectGoodsMap" resultType="java.util.LinkedHashMap">
        select gs.*, ca.category_name, '1' as test from t_goods gs, t_category ca where gs.category_id = ca.category_id;
    </select>
02. testSelectGoodsMap()
java 复制代码
    @Test
    public void testSelectGoodsMap() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            List<Map> list = sqlSession.selectList("goods.selectGoodsMap");
            for(Map map: list){
                System.out.println(map);
            }
        }catch (Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }
03. 实现效果

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

{goods_id=739, title=亲润 孕妇护肤品豆乳大米盈润保湿胶原蚕丝面膜(18片装), sub_title=卓效对抗孕期干燥,15分钟快速补水,补充胶原蛋白,幼滑肌肤。天然豆乳配方,温和低敏,孕产期、所有肤质适用。, original_cost=198.0, current_price=88.0, discount=0.444444, is_free_delivery=1, category_id=43, category_name=米粉, test=1}

{goods_id=740, title=爱恩幼 孕妇护肤品润养颜睡眠面膜 100g, sub_title=免洗配方,质地清透不黏腻,睡眠间为肌肤持续补充营养,并牢牢锁住水分,清晨醒来后,肌肤水润柔嫩,洋溢青春活力。, original_cost=96.0, current_price=49.0, discount=0.510417, is_free_delivery=1, category_id=44, category_name=牙胶/咬咬乐, test=1}

...

3.2 ResultMap 结果映射

01. 新建dto 数据传输对象
java 复制代码
package com.phdvb.mybatis.dto;

import com.phdvb.mybatis.entity.Goods;

// dto --> 数据传输对象
public class GoodsDTO {
    private Goods goods = new Goods();
    private String categoryName;
    private String test;

    public Goods getGoods() {
        return goods;
    }

    public void setGoods(Goods goods) {
        this.goods = goods;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}
02. 编写测试类
java 复制代码
@Test
    public void testSelectGoodsDTO() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            List<GoodsDTO> list = sqlSession.selectList("goods.selectGoodsDTO");
            for(GoodsDTO goods: list){
                System.out.println(goods.getGoods().getSubTitle());
            }
        }catch (Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }
03. 运行效果

3.3 ResultMap 进一步的封装

01. Category
java 复制代码
package com.phdvb.mybatis.entity;

public class Category {
    private Integer categoryId;
    private String categoryName;
    private Integer parentId;
    private Integer categoryLevel;
    private Integer categroyOrder;

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public Integer getCategoryLevel() {
        return categoryLevel;
    }

    public void setCategoryLevel(Integer categoryLevel) {
        this.categoryLevel = categoryLevel;
    }

    public Integer getCategroyOrder() {
        return categroyOrder;
    }

    public void setCategroyOrder(Integer categroyOrder) {
        this.categroyOrder = categroyOrder;
    }
}
02. 完善GoodsDTO
java 复制代码
package com.phdvb.mybatis.dto;

import com.phdvb.mybatis.entity.Category;
import com.phdvb.mybatis.entity.Goods;

// dto --> 数据传输对象
public class GoodsDTO {
    private Goods goods = new Goods();
//    private String categoryName;
    private Category category = new Category();
    private String test;

    public Goods getGoods() {
        return goods;
    }

    public void setGoods(Goods goods) {
        this.goods = goods;
    }
    
    public Category getCategory() {
        return category;
    }
    
    public void setCategory(Category category) {
        this.category = category;
    }
//    public String getCategoryName() {
//        return categoryName;
//    }
//
//    public void setCategoryName(String categoryName) {
//        this.categoryName = categoryName;
//    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}
03. goods.xml
java 复制代码
    <!--结果映射-->
    <resultMap id="rmGoods" type="com.phdvb.mybatis.dto.GoodsDTO">
        <!--设置主键字段与属性映射-->
        <id property = "goods.goodsId" column="goods_id"></id>
        <!--设置非主键字段与属性映射-->
        <result property="goods.title" column="title"></result>
        <result property="goods.subTitle" column="sub_title"></result>
        <result property="goods.originalCost" column="original_cost"></result>
        <result property="goods.currentPrice" column="current_price"></result>
        <result property="goods.discount" column="discount"></result>
        <result property="goods.isFreeDelivery" column="is_free_delivery"></result>
<!--        <result property="goods.categoryId" column="category_id"></result>-->
<!--        <result property="categoryName" column="category_name"></result>-->
        <result property="category.categoryId" column="category_id"></result>
        <result property="category.categoryName" column="category_name"></result>
        <result property="category.parentId" column="parent_Id"></result>
        <result property="category.categoryLevel" column="category_level"></result>
        <result property="category.categoryOrder" column="category_order"></result>
        <result property="test" column="test"></result>
    </resultMap>

    <select id="selectGoodsDTO" resultMap="rmGoods">
        select gs.*, ca.*, '1' as test from t_goods gs, t_category ca where gs.category_id = ca.category_id;
    </select>
04. 运行效果

4. 数据插入

4.1数据库事务 与 insertDemo

4.2 goods.xml

XML 复制代码
<!--插入数据-->
    <insert id="insertGoods" parameterType="com.phdvb.mybatis.entity.Goods">
        insert into t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id)
        values (#{title}, #{subTitle}, #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}, #{categoryId})
    </insert>

4.3.testInsertGoods()

java 复制代码
@Test
    public void testInsertGoods() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            Goods goods = new Goods();
            goods.setTitle("华为蓝牙耳机");
            goods.setSubTitle("feel good!");
            goods.setOriginalCost(109f);
            goods.setCurrentPrice(99f);
            goods.setDiscount(0.6f);
            goods.setIsFreeDelivery(1);
            goods.setCategoryId(43);
            int rows = sqlSession.insert("goods.insertGoods", goods);
            // 提交事务 数据
            sqlSession.commit();
            System.out.println(goods.getGoodsId() + "-"+ goods.getTitle());
        }catch (Exception e){
            if(sqlSession != null){
                // 回滚事务
                sqlSession.rollback();
            }
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }

4.4 新增Id无法获取

4.5 selectKey完善good.xml

XML 复制代码
<!--插入数据-->
    <insert id="insertGoods" parameterType="com.phdvb.mybatis.entity.Goods">
        insert into t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id)
        values (#{title}, #{subTitle}, #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}, #{categoryId})
        <selectKey resultType="Integer" keyProperty="goodsId" order="AFTER">
            select last_insert_id();
        </selectKey>
    </insert>

4.5 useGeneratedKeys完善good.xml

XML 复制代码
 <!--useGeneratedKeys完善插入数据-->
    <insert id="insertGoods"
            parameterType="com.phdvb.mybatis.entity.Goods"
            useGeneratedKeys="true"
            keyProperty="goodsId"
            keyColumn="goods_id">
        insert into t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id)
        values (#{title}, #{subTitle}, #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}, #{categoryId})
    </insert>

4.6 selectKey与useGeneratedKeys的区别

5. 更新数据

5.1 baseDemo

5.2 goods.xml

XML 复制代码
<!--更新操作-->
    <update id="updateGoods" parameterType="com.phdvb.mybatis.entity.Goods">
        update t_goods
        set
            title =  #{title},
            sub_title = #{subTitle},
            original_cost = #{originalCost},
            current_price = #{currentPrice},
            discount = #{discount},
            is_free_delivery = #{isFreeDelivery},
            category_id = #{categoryId}
        where
            goods_id = #{goodsId}
    </update>

5.3 testUpdateGoods()

java 复制代码
@Test
    public void testUpdateGoods() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            Goods goods = sqlSession.selectOne("goods.selectById", 739);
            goods.setTitle("更新为华为蓝牙耳机");
            sqlSession.update("goods.updateGoods", goods);
            // 提交事务 数据
            sqlSession.commit();
            System.out.println(goods.getGoodsId() + "-"+ goods.getTitle());
        }catch (Exception e){
            if(sqlSession != null){
                // 回滚事务
                sqlSession.rollback();
            }
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }

6. 删除数据

6.1 baseDemo

6.2 goods.xml

XML 复制代码
    <!--删除数据-->
    <delete id="deleteGoods" parameterType="Integer">
        delete from t_goods where goods_id = #{value}
    </delete>

6.3 deleteUpdateGoods()

java 复制代码
@Test
    public void deleteUpdateGoods() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            int num = sqlSession.delete("goods.deleteGoods", 739);
            // 提交事务 数据
            sqlSession.commit();
        }catch (Exception e){
            if(sqlSession != null){
                // 回滚事务
                sqlSession.rollback();
            }
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }

7. Mybatis 预防SQL注入攻击

7.1 baseDemo

7.2 MyBatis 的两种传值方式

7.3 goods.xml

XML 复制代码
    <!--测试SQL注入-->
    <select id="selectByTitle" parameterType="java.util.Map" resultType="com.phdvb.mybatis.entity.Goods">
        select * from t_goods where title = #{title}
    </select>

    <select id="selectByTitleAndOrder" parameterType="java.util.Map" resultType="com.phdvb.mybatis.entity.Goods">
        select * from t_goods where title = ${title}
    </select>

7.4 testSelectByTitle01(#{})

java 复制代码
@Test
    public void testSelectByTitle01() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            Map param = new HashMap();
            param.put("title","'爱恩幼 孕妇护肤品润养颜睡眠面膜 100g'");
            List<Goods> list = sqlSession.selectList("goods.selectByTitle", param);
            for(Goods goods: list){
                System.out.println(goods.getSubTitle() + ":" + goods.getDiscount());
            }
        }catch (Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }

没有输出

7.5 testSelectByTitle02()
java 复制代码
@Test
    public void testSelectByTitle02() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.openSession();
            Map param = new HashMap();
            param.put("title","'爱恩幼 孕妇护肤品润养颜睡眠面膜 100g'");
            List<Goods> list = sqlSession.selectList("goods.selectByTitleAndOrder", param);
            for(Goods goods: list){
                System.out.println(goods.getSubTitle() + ":" + goods.getDiscount());
            }
        }catch (Exception e){
            throw e;
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }
相关推荐
kakwooi2 分钟前
易乐播播放器---压力测试
java·jmeter·测试
昵称为空C11 分钟前
SpringBoot 实现DataSource接口实现多租户数据源切换方案
后端·mybatis
hqwest25 分钟前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
NEUMaple36 分钟前
python爬虫(四)----requests
开发语言·爬虫·python
sufu106537 分钟前
说说内存泄漏的常见场景和排查方案?
java·开发语言·面试
羊锦磊1 小时前
[ CSS 前端 ] 网页内容的修饰
java·前端·css
hrrrrb1 小时前
【Java Web 快速入门】九、事务管理
java·spring boot·后端
bluebonnet271 小时前
【Python】一些PEP提案(六):元类、默认 UTF-8、Web 开发
开发语言·前端·python
我不是立达刘宁宇2 小时前
php危险函数,二.assert()[现版本已弃用]
开发语言·php