mybatis快速入门(小例子)

笔记

在这里插入图片描述

1、创表

create database mybatis;
use mybatis;

drop table if exists tb_user;

create table tb_user(
	id int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	gender char(1),
	addr varchar(30)
);

INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');

2、创建项目,模块,导入坐标

1、创建空项目

在这里插入图片描述

2、新建模块

在这里插入图片描述

3、新建maven项目

在这里插入图片描述
新建后的pom文件
在这里插入图片描述

4、导入坐标

mybatis官网

3、pom文件中导入的依赖,编写配置文件

<?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>org.example</groupId>
    <artifactId>mybatis-demos</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!--mybatis的依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!--junit单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!-- 添加slf4j日志api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
        </dependency>
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>

    </dependencies>

</project>

1、logback依赖添加后,还需要一个配置文件,放在resources目录下

在这里插入图片描述
logback配置文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        CONSOLE :表示当前的日志信息是可以输出到控制台的。
    -->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="com.itheima" level="DEBUG" additivity="false">
        <appender-ref ref="Console"/>
    </logger>


    <!--

      level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
     , 默认debug
      <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
      -->
    <root level="DEBUG">
        <appender-ref ref="Console"/>
    </root>
</configuration>

2、创建mybatis-config.xml配置文件,放在resources目录下

在这里插入图片描述

<?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="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库连接信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="******"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载sql映射文件,是在平级,直接写文件名即可-->
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

4、编写sql映射文件

1、创建UserMapper.xml配置文件,放在resources目录下(要操作哪个表,就以哪个表命名)

<?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">

<!--
    namespace:名称空间
-->
<mapper namespace="test">
	<!--id是唯一标识,现在我们要查询所有,所以用selectAll-->
	<!--resultType是返回类型,这里查询的是全部用户,所以应该返回一个用户类,这里先写一个User类-->
    <select id="selectAll" resultType="com.itheima.pojo.User">
        select * from tb_user;
    </select>
</mapper>

此时我们已经写好了sql映射文件,下面再将其加载进mybatis-config.xml文件中
在这里插入图片描述

5、编码

1、定义pojo类

User类,跟数据库表中的数据一样

package com.itheima.pojo;

public class User {

    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}

2、写核心测试类

package com.itheima;

import com.itheima.pojo.User;
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.InputStream;
import java.util.List;

/*
*mybatis快速入门代码
* */
public class MyBatisDemo {
    public static void main(String[] args) throws IOException {
        //1加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3执行sql,查询所有就用sqlSession的selectList方法,查询单个就是selectOne
        //要执行的sql语句,只需要传入对应的唯一标识即可:名称空间.唯一标识
        List<User> users = sqlSession.selectList("test.selectAll");
        System.out.println(users);

        //4释放资源
        sqlSession.close();
    }
}

6、在idea中配置mysql数据库连接

在这里插入图片描述
填入信息
在这里插入图片描述
download
在这里插入图片描述
解决时区问题

完成
在这里插入图片描述
解决连接数据库后写sql代码不提示表名

7、Mapper代理开发

在这里插入图片描述

1、创建Mapper接口并将其和sql映射文件置于同一目录下

1、创建Mapper接口

在这里插入图片描述在这里插入图片描述

2、将Mapper接口和SQL映射文件放在同一目录下

在resources目录下创建包com.itheima.mapper
在这里插入图片描述
将UserMapper.xml配置文件放入新建的包后编译,结果在同一目录下
在这里插入图片描述
在这里插入图片描述

2、将SQL映射文件的namespqce属性为Mapper接口全限定名

在这里插入图片描述

3、在 Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致

在这里插入图片描述
在这里插入图片描述
此时,sql映射文件的路径发生改变,所以要在mybatis配置文件中更改文件路径
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4、编码

通过SqlSession的 getMapper方法获取Mapper接口的代理对象,代理对象调用对应方法完成sql的执行

package com.itheima;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
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.InputStream;
import java.util.List;

/*
* mybatis代理开发
* */
public class MyBatisDemo2 {
    public static void main(String[] args) throws IOException {
        //1加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3执行sql
        //List<User> users = sqlSession.selectList("test.selectAll");

        //3.1获取UserMapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = userMapper.selectAll();

        System.out.println(users);

        //4释放资源
        sqlSession.close();
    }
}

细节:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载

    <mappers>
        <!--加载sql映射文件,copy path,选择Source root-->
        <!--<mapper resource="com\itheima\mapper\UserMapper.xml"/>-->
        
        <!--mapper代理方式-->
        <package name="com.itheima.mapper"/>
        
    </mappers>

8、增删改查应用

1、mapper下新建接口文件

在这里插入图片描述

2、resource下新建配置文件并编写sql代码

在这里插入图片描述

3、编写测试用例

package com.itheima.test;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
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.InputStream;
import java.util.List;

public class MyBatisTest {

    @Test
    public void testSelectAll() throws IOException {
        //1.加载mybatis核心配置文件,获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SQLSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        List<Brand> brands = brandMapper.selectAll();
        System.out.println(brands);
        //5.释放资源
        sqlSession.close();
    }
}

4、解决数据库表字段名称和实体类的属性名称不一致的问题

<mapper namespace="com.itheima.mapper.BrandMapper">
    <!--
        数据库表的字段名称和实体类的属性名称不一样就不能自动封装数据
        1、对不一样的列名起别名,让别名和实体类的属性名一样
            缺点:每次查询都要定义一次别名
                解决:使用sql片段
                    缺点:不灵活
        2、resultMap:新增<resultMap>标签,id为唯一标识,type映射的类型,支持别名
        resultMap标签内的id指的是主键字段的映射,result是一般字段的映射
        column表的列名,property指的是实体类的字段
    -->

//   原始
    <select id="selectAll" resultType="com.itheima.pojo.Brand">
        select *
        from tb_brand;
    </select>


//    sql片段
    <sql id="brand_column">
        id, brand_name as brandName, company_name as companyName, ordered, description, status
    </sql>

    <select id="selectAll" resultType="com.itheima.pojo.Brand">
        select
            <include refid="brand_column"></include>
        from tb_brand;
    </select>

//    resultMap
	<!--
		1、定义<resultMap>标签
		2、在<select>标签中使用resultMap属性替换resultType属性
	-->
    <resultMap id="brandResultMap" type="com.itheima.pojo.Brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>
    
	<!--<select id="selectAll" resultType="com.itheima.pojo.Brand">要把type更改为resultMap-->
    <select id="selectAll" resultMap="brandResultMap">
        select *
        from tb_brand;
    </select>
</mapper>

5、按id单个查询

1、参数占位符:
1)#{},执行sQL时,会将#沿占位符替换为?,将来自动设置参数值
2)${},拼SQL,会存在sQL注入问题。
3)使用时机:
	*参数传递,都使用#{}
	*如果要对表名、列名进行动态设置,只能使用${}进行sql拼接。
2、parameterType:
*用于设置参数类型,该参数可以省略
3、SQL语句中特殊字符处理:
*转义字符
<![CDATA[内容]]>

6、多条件查询

    /*
    * 条件查询
    *   参数接收
    *       1、散装参数:如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)
    *       2、对象参数:对象的属性名要和sql参数占位符名称一致
    *       3、map集合参数:map集合的属性名要和sql参数占位符名称一致
    * @Param status
    * @Param companyName
    * @Param brandName
    * */

    /* 散装参数
    List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName, @Param("brandName") String brandName);
    */

    /*对象参数
    List<Brand> selectByCondition(Brand brand);
    */

    /*map集合参数*/
    List<Brand> selectByCondition(Map map);
    <!--多条件查询-->
    <select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        where status=#{status}
          and company_name like #{companyName}
          and brand_name like #{brandName};
    </select>
    public void testSelectByCondition() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "华为";
        String brandName = "华为";
        //处理参数
        companyName = "%"+companyName+"%";
        brandName = "%"+brandName+"%";

        //封装对象
        /*
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        */
		
		//创建集合
        Map map = new HashMap();
        map.put("status", status);
        map.put("companyName", companyName);
        map.put("brandName", brandName);

        //1.加载mybatis核心配置文件,获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SQLSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        //散装
        //List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);

        //对象
        //List<Brand> brands = brandMapper.selectByCondition(brand);

        //map
        List<Brand> brands = brandMapper.selectByCondition(map);
        System.out.println(brands);
        //5.释放资源
        sqlSession.close();
    }

7、动态条件查询

1、多条件动态查询
    <!--
        动态条件查询
            if:条件判断
                test:逻辑表达式
            问题:当第一个条件没填写时,后面的“and“会产生语法错误
                1、恒等式 1=1
                2、<where>替换where关键字,可以自动修正格式错误
    -->
    <!--   1、恒等式
    <select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        where 1=1
            <if test="status != null">
                and status=#{status}
            </if>
            <if test="companyName != null and companyName != ''">
                and company_name like #{companyName}
            </if>
            <if test="brandName != null and brandName != ''">
                and brand_name like #{brandName};
            </if>
    </select>
    -->

    <!--<where>标签-->
    <select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        <where>
            <if test="status != null">
                and status=#{status}
            </if>
            <if test="companyName != null and companyName != ''">
                and company_name like #{companyName}
            </if>
            <if test="brandName != null and brandName != ''">
                and brand_name like #{brandName};
            </if>
        </where>
    </select>
2、单条件动态查询
    /*单条件动态查询,要封装在对象里*/
    List<Brand> selectByConditionSingle(Brand brand);

    public void testSelectByConditionSingle() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "华为";
        String brandName = "华为";
        //处理参数
        companyName = "%"+companyName+"%";
        brandName = "%"+brandName+"%";

        //封装对象,这三个任选一个或者都不选也可
        Brand brand = new Brand();
        //brand.setStatus(status);
        brand.setCompanyName(companyName);
        //brand.setBrandName(brandName);

        //1.加载mybatis核心配置文件,获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SQLSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        //对象
        List<Brand> brands = brandMapper.selectByConditionSingle(brand);
        System.out.println(brands);
        //5.释放资源
        sqlSession.close();
    }
    <!--单条件动态查询,假如用户一个都不选,则必须要用otherwise-->
    <select id="selectByConditionSingle" resultMap="brandResultMap">
        select *
        from tb_brand
        where
        <choose><!--相当于switch-->
            <when test="status != null"><!--相当于case-->
                status=#{status}
            </when>
            <when test="companyName != null and companyName != ''"><!--相当于case-->
                company_name like #{companyName}
            </when>
            <when test="brandName != null and brandName != ''"><!--相当于case-->
                brand_name like #{brandName}
            </when>
            <otherwise>
                1 = 1
            </otherwise>
        </choose>
    </select>

    <!--或者也可以直接使用<where>标签自动修正sql语法错误,就不用写otherwise-->
    <!--
    <select id="selectByConditionSingle" resultMap="brandResultMap">
        select *
        from tb_brand
        <where>
            <choose>
                <when test="status != null">
                    status=#{status}
                </when>
                <when test="companyName != null and companyName != ''">
                    company_name like #{companyName}
                </when>
                <when test="brandName != null and brandName != ''">
                    brand_name like #{brandName}
                </when>
            </choose>
        </where>
    </select>
    -->

8、添加、修改

    <!--插入时,id自动生成,但是并未赋值给该条数据的id,需要配置属性-->
    <!--
    <insert id="add">
        insert into tb_brand (brand_name, company_name, ordered, description, status)
        values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
    </insert>
    -->

    <!--想要返回主键,配置useGeneratedKeys和keyProperty两个属性即可-->
    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into tb_brand (brand_name, company_name, ordered, description, status)
        values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
    </insert>


    <!--修改全部字段-->
    <!--
    <update id="update">
        update tb_brand
        set
            brand_name = #{brandName},
            company_name = #{companyName},
            ordered = #{ordered},
            description = #{description},
            status = #{status}
        where id = #{id};
    </update>
    -->

    <!--动态修改字段,只更改其中几个字段,为了防止sql报错-->
    <update id="update">
        update tb_brand
        <set>
            <if test="brandName != null and brandName != ''">
                brand_name = #{brandName},
            </if>
            <if test="companyName != null and companyName != ''">
                company_name = #{companyName},
            </if>
            <if test="ordered != null">
                ordered = #{ordered},
            </if>
            <if test="description != null and description != ''">
                description = #{description},
            </if>
            <if test="status != null">
                status = #{status}
            </if>
        </set>
        where id = #{id};
    </update>
//添加和修改,传入的都是一个对象
    /*添加*/
    void add(Brand brand);

    /*修改*/
    void update(Brand brand);

    @Test
    public void testAdd() throws IOException {
        //接收参数
        String brandName = "波导手机";
        String companyName = "波导";
        int ordered = 100;
        String description = "手机中的战斗机";
        int status = 1;

        //封装对象
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        brand.setStatus(status);

        //1.加载mybatis核心配置文件,获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SQLSession对象
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //自动提交事务,传递参数true即可
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        //对象
        brandMapper.add(brand);
        //手动提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }

    @Test
    public void testAdd2() throws IOException {//返回主键
        //接收参数
        String brandName = "波导手机";
        String companyName = "波导";
        int ordered = 100;
        String description = "手机中的战斗机";
        int status = 1;

        //封装对象
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        brand.setStatus(status);

        //1.加载mybatis核心配置文件,获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SQLSession对象
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //自动提交事务,传递参数true即可
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        //对象
        brandMapper.add(brand);
        Integer id = brand.getId();
        System.out.println(id);
        //手动提交事务
        //sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }

    @Test
    public void testUpdate() throws IOException {//返回主键
        //接收参数
        String brandName = "波导手机";
        String companyName = "波导";
        int ordered = 200;
        String description = "波导手机,手机中的战斗机";
        int status = 0;
        int id = 6;

        //封装对象
        Brand brand = new Brand();
//        brand.setBrandName(brandName);
//        brand.setCompanyName(companyName);
//        brand.setOrdered(ordered);
//        brand.setDescription(description);
        brand.setStatus(status);
        brand.setId(id);

        //1.加载mybatis核心配置文件,获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SQLSession对象
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //自动提交事务,传递参数true即可
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        //对象
        brandMapper.update(brand);

        //手动提交事务
        //sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }

9、删除

1、单个删除
    <delete id="deleteById">
        delete from tb_brand where id = #{id};
    </delete>
    /*删除单个*/
    void deleteById(int id);

    @Test
    public void testDeleteById() throws IOException {
        //接收参数
        int id = 7;

        //1.加载mybatis核心配置文件,获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SQLSession对象
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //自动提交事务,传递参数true即可
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        //对象
        brandMapper.deleteById(id);
        //手动提交事务
        //sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
2、批量删除
    <!--
    mybatis会将数组参数封装成一个Map集合
    *默认
        key   -  value
        array -  数组
    *使用@param注解改变默认集合的默认key名称
    -->
    <!--
    <delete id="deleteByIds">
        delete from tb_brand where id
        in (
            <foreach collection="ids" item="id" separator=",">
                #{id}
            </foreach>
            );
    </delete>
    -->

    <!--通过open和close标签完成前后的拼接-->
    <delete id="deleteByIds">
        delete from tb_brand where id
        in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
        ;
    </delete>
    /*批量删除*/
    void deleteByIds(@Param("ids") int[] ids);

    @Test
    public void testDeleteByIds() throws IOException {
        //接收参数
        int[] ids = {6,8,9};

        //1.加载mybatis核心配置文件,获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SQLSession对象
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //自动提交事务,传递参数true即可
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        //对象
        brandMapper.deleteByIds(ids);
        //手动提交事务
        //sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值