Javaweb基础5—Mybatis的使用

Mybatis目录

例如:JavaWeb基础之Mybatis的使用



Mybatis简介

在这里插入图片描述

  • 表现层:页面展示
  • 业务层:逻辑处理
  • 持久层:数据持久化的

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


一、Mybatis快速入门


编写mybatis核心配置文件,替换连接信息

<?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"></transactionManager>
            <dataSource type="POOLED">
                <!--数据库连接信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载SQL的映射文件-->
        <mapper resource="UserMapper.xml" />
    </mappers>
</configuration>

编写SQL映射文件,统一管理SQL语句

<?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">
    <select id="selectAll" resultType="org.example.pojo.User">
        select * from tb_user;
    </select>

</mapper>

进行编码,执行JDBC的步骤

  1. 加载mybatis配置文件,完成的功能有
    • 连接数据库
    • 定义SQL语句
    • 获取执行SQL的任务对象
  2. 执行SQL
  3. 处理结果
  4. 释放资源(为SQLSession对象)
package org.example;

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.example.pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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

        //2.获取SqlSession对象,用它来执行SQL语句
        SqlSession session = sqlSessionFactory.openSession();

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

        //处理结果
        System.out.println(users);

        //释放资源
        session.close();
    }
}

依赖管理

<?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-demo</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!-- mybatis的依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!--mysql 驱动包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</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>

日志管理

<?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>
package org.example.pojo;

public class User {

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", addr='" + 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;
    }
}

在这里插入图片描述

二、Mapper代理开发

在这里插入图片描述

在这里插入图片描述

  1. 创建Mapper接口并将SQL文件放在与Mapper接口同一目录下
package org.example.mapper;

import org.example.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> selectAll();
}

在这里插入图片描述

  1. 设置namespace的属性为Mapper接口全限定名
<?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="org.example.mapper.UserMapper">
    <select id="selectAll" resultType="org.example.pojo.User">
        select * from tb_user;
    </select>

</mapper>
  1. 定义Mapper接口中的方法
  2. 通过SQLSession的getMapper方法获取Mapper接口的代理对象
  3. 调用对应方法完成SQL执行
  4. 修改mybatis配置文件中SQL映射文件的加载
package org.example;

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.example.mapper.UserMapper;
import org.example.pojo.User;

import java.io.InputStream;
import java.util.List;

/**
        mybatis的代理开发
 */
public class MybatisDemo2 {
    public static void main(String[] args) throws Exception {
        //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 = session.selectList("test.selectAll");

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

        //处理结果
        System.out.println(users);

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


三、Mybatis核心配置文件

在这里插入图片描述
可以设置多个数据源,并通过default属性进行切换

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

    
<!--    起别名,默认不用带包名称并且别名为小写,SQL配置文件可以直接写小写的类名称-->
    <typeAliases>
        <package name="org.example.pojo"/>
    </typeAliases>
    
<!--    environment:配置数据库环境信息:可以配置多个environment,通过default来切换不同的environment-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <!--数据库连接信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment><!--
        <environment id="test">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                &lt;!&ndash;数据库连接信息&ndash;&gt;
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
-->
    </environments>
    <mappers>
        <!--加载SQL的映射文件-->
<!--        <mapper resource="org\example\mapper\UserMapper.xml" />-->

<!--        Mapper代理方式-->
        <package name="org.example.mapper"/>
    </mappers>
</configuration>

四、配置文件完成增删改查

在这里插入图片描述

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

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

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

<?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="org.example.mapper.BrandMapper">
    <!--
            数据库表的字段名    和   实体类的属性名不一样,则不能自动封装数据
            方法一:起别名 对不一样的列名起别名,让别名和实体类的属性名一样
                   缺点:每次查询都要定义一次别名
                        解决方案:SQL片段
                                缺点:不灵活
            方法二:resultMap
                    1. 定义<resultMap>标签
                    2. 在<select>标签中,使用resultMap属性替换 resultType属性
                type:映射的类型,支持别名
                id:唯一标识
    -->

    <resultMap id="BrandResultMap" type="brand">
        <result column="brand_name" property="brandName"/>
        <!--
        id :完成主键字段映射
            column:表的列名
            property:实体类的属性名
        result: 完成一般字段的映射
            column:表的列名
            property:实体类的属性名
        -->
        <result column="company_name" property="companyName"/>
    </resultMap>



    <select id="selectAll" resultMap="BrandResultMap">
        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="brand">
         select
         <include refid="brand_column"/>
          from tb_brand;
     </select>-->


    <!-- <select id="selectAll" resultType="brand">
         select id, brand_name as brandName,
         company_name as companyName,
         ordered, description, status from tb_brand;
     </select>-->

    <!-- <select id="selectAll" resultType="brand">
         select * from tb_brand;
     </select>-->


    <!--
        参数占位符:
            1.#{}:会将其替换为?,为了防止SQL注入
            2.${}:拼接SQL,会存在SQL注入问题
            3.使用时机:
                参数传递的时候:#{}
                表名或者列名不固定的情况下:${}
        参数类型:parameterType  可以省略不写
        特殊字符处理:
            1、转义字符
            2.CDATA区
    -->


    <!--CDATA区-->
    <!-- <select id="selectById" resultMap="BrandResultMap">
         select * from tb_brand where id
         <![CDATA[
                  <
         ]]>  #{id};
     </select>-->

    <!--转义字符-->
    <!-- <select id="selectById"  resultMap="BrandResultMap">
         select * from tb_brand where id &lt;  #{id};
     </select>-->
    <select id="selectById" resultMap="BrandResultMap">
        select * from tb_brand where id=#{id};
    </select>

    <!--条件查询-->
    <!--
        <select id="selectByCondition" resultMap="BrandResultMap">
            select * from tb_brand where
            status = #{status}
            and company_name like #{companyName}
            and brand_name like #{brandName};
        </select>-->

    <!--动态条件查询
        if:条件判断
            test:逻辑表达式
        问题:
            1、恒等式
            2、<where>标签

    -->
    <!--<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>-->

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


    <!--<select id="selectByConditionSingle" resultMap="BrandResultMap">
         select * from tb_brand where
          <choose> &lt;!&ndash; 相当于Switch&ndash;&gt;
             <when test="status != null">&lt;!&ndash; 相当于case&ndash;&gt;
                 status = #{status}
             </when>
             <when test="companyName != null and companyName != ''">&lt;!&ndash; 相当于case&ndash;&gt;
                 company_name=#{companyName}
             </when>
             <when test="brandName != null and brandName != ''">&lt;!&ndash; 相当于case&ndash;&gt;
                 brand_name like #{brandName}
             </when>
             <otherwise>&lt;!&ndash; 相当于default&ndash;&gt;
                 1=1
             </otherwise>
         </choose>
    </select>-->

    <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=#{companyName}
                </when>
                <when test="brandName != null and brandName != ''"><!-- 相当于case-->
                    brand_name like #{brandName}
                </when>
            </choose>
        </where>
    </select>


    <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>
            <if test="status != null">
                status=#{status},
            </if>
            <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>
        </set>
        where id=#{id};
    </update>



    <delete id="deleteById">
        delete from tb_brand where id=#{id};
    </delete>


    <!--
            mybatis会将数组参数,封装为一个Map集合
                默认:array = 数组
                使用@Param注解来改变map集合的默认key的名称
    -->
    <delete id="deleteByIds">
        delete from tb_brand
        where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
</mapper>
package org.example.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.example.pojo.Brand;
import org.example.pojo.User;

import java.util.List;
import java.util.Map;

public interface BrandMapper {
    /**
     * 查看所有
     * @return
     */
    List<Brand> selectAll();

    /**
     * 查看详情
     * @param id
     * @return
     */
    Brand selectById(int id);


    /**
     * 条件接收:
     *      参数接收:
     *          1、散装参数  如果方法中有多个参数,要使用@Param注解(SQL参数占位符名称)
     *          2、对象参数
     *          3、map集合参数
     */
    /*
    List<Brand> selectByCondition(@Param("status") int status,@Param("companyName") String companyName, @Param("brandName") String brandName);
    */
/*
    List<Brand> selectByCondition(Brand brand);
    */
    List<Brand> selectByCondition(Map mapper1);


    /**
     * 单条件的动态查询
     * @param brand
     * @return
     */
    List<Brand> selectByConditionSingle(Brand brand);

    /**
     * 添加
     * @param brand
     */
    void add(Brand brand);

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

    /**
     * 根据id删除
     */

    void deleteById(int id);

    /**
     * 批量删除
     */
    void deleteByIds(@Param("ids") int[] ids);
}

package org.example.test;

import org.apache.ibatis.annotations.Mapper;
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.example.mapper.BrandMapper;
import org.example.pojo.Brand;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MybatisTest {
    @Test
    public void testSelectAll() throws Exception {
        //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 mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        List<Brand> brands = mapper.selectAll();
        System.out.println(brands);

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


    @Test
    public void testSelectById() throws Exception {
        //接受参数
        int id =3;

        //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 mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        Brand brand =  mapper.selectById(id);
        System.out.println(brand);

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

    /**
    * 使用多参数值
    * */

/*
    @Test
    public void testSelectByCondition() throws Exception {
        //接受参数
        int status=1;
        String brandName= "华为";
        String companyName= "华为";

        //处理参数
        brandName = "%"+brandName+"%";
        companyName = "%"+ companyName +"%";


        //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 mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        List<Brand> brands = mapper.selectByCondition(status, companyName, brandName);
        System.out.println(brands);

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


    /**
    * 使用对象封装
    * */
    /*
    @Test
    public void testSelectByCondition() throws Exception {
        //接受参数
        int status=1;
        String brandName= "华为";
        String companyName= "华为";

        //处理参数
        brandName = "%"+brandName+"%";
        companyName = "%"+ companyName +"%";

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

        //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 mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        List<Brand> brands = mapper.selectByCondition(brand);
        System.out.println(brands);

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

    /**
     * 使用Map
     * @throws Exception
     */
    @Test
    public void testSelectByCondition() throws Exception {
        //接受参数
        int status=1;
        String brandName= "华为";
        String companyName= "华为";

        //处理参数
        brandName = "%"+brandName+"%";
        companyName = "%"+ companyName +"%";

        //创建Mapper
        Map mapper1 = new HashMap();
       // mapper1.put("status",status);
        mapper1.put("brandName",brandName);
        //mapper1.put("companyName",companyName);

        //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 mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        List<Brand> brands = mapper.selectByCondition(mapper1);
        System.out.println(brands);

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


    /**
     * 单条件查询
     * @throws Exception
     */
    @Test
    public void testSelectByConditionSingle() throws Exception {
        //接受参数
        int status=1;
        String brandName= "华为";
        String companyName= "华为";

        //处理参数
        brandName = "%"+brandName+"%";
        companyName = "%"+ companyName +"%";

        //封装对象
        Brand brand=new Brand();
        //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();

        //3.使用Mapper代理
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        List<Brand> brands = mapper.selectByConditionSingle(brand);
        System.out.println(brands);

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


    @Test
    public void testAdd() throws Exception {
        //接受参数
        int status=1;
        String brandName= "苹果";
        String companyName= "苹果手机";
        int ordered=100;
        String deception="苹果手机比较好用";

        //处理参数
       /* brandName = "%"+brandName+"%";
        companyName = "%"+ companyName +"%";*/

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


        //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();

        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.使用Mapper代理
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        mapper.add(brand);


        //提交事务
        //sqlSession.commit();

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


    /**
     * 主键返回的添加数据
     * @throws Exception
     */

    @Test
    public void testAdd2() throws Exception {
        //接受参数
        int status=1;
        String brandName= "苹果";
        String companyName= "苹果手机";
        int ordered=100;
        String deception="苹果手机比较好用";

        //处理参数
       /* brandName = "%"+brandName+"%";
        companyName = "%"+ companyName +"%";*/

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


        //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();

        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.使用Mapper代理
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        mapper.add(brand);
        int id=brand.getId();
        System.out.println(id);


        //提交事务
        //sqlSession.commit();

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


    @Test
    public void testUpdate() throws Exception {
        //接受参数
        int status=1;
        String brandName= "苹果";
        String companyName= "苹果手机";
        int ordered=200;
        String deception="苹果手机太烂";
        int id=6;
        //处理参数
       /* brandName = "%"+brandName+"%";
        companyName = "%"+ companyName +"%";*/

        //封装对象
        Brand brand=new Brand();
        brand.setStatus(status);
       /* brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(deception);
        brand.setOrdered(ordered);*/
        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();

        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.使用Mapper代理
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        int update = mapper.update(brand);
        System.out.println(update);


        //提交事务
        //sqlSession.commit();

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



    @Test
    public void testDeleteById() throws Exception {

        int id=6;


        //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();

        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.使用Mapper代理
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        mapper.deleteById(id);


        //提交事务
        //sqlSession.commit();

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


    @Test
    public void testDeleteByIds() throws Exception {

        int[] ids={5,7,8};


        //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();

        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.使用Mapper代理
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行SQL
        mapper.deleteByIds(ids);


        //提交事务
        //sqlSession.commit();

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

在这里插入图片描述

在这里插入图片描述

五、注解完成增删改查

在这里插入图片描述

总结

主要学会Mapper代理开发和动态SQL书写

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值