MyBatis

MyBatis

概念
  • MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
  • 官网:https://mybatis.org/mybatis-3/zh/index.html
持久层
  • 负责将数据保存到数据库的那一层代码
  • JavaEE三层架构:表现层、业务层、持久层
框架
  • 框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码结构
  • 在框架的基础之上构建软件编写更加高效、规范、通用、可扩展

MyBatis快速入门

查询user表中的所有数据
  1. 创建user表,添加数据

  2. 创建模块,导入坐标

    <?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.zxx</groupId>
        <artifactId>MyBatis_Study</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
        </properties>
    
        <dependencies>
            <!--MySql 驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.32</version>
            </dependency>
    
            <!-- MyBatis 依赖-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.5</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.36</version>
                <scope>test</scope>
            </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>
    
  3. 编写MyBatis核心配置文件 --> 替换连接信息,解决硬编码问题

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <!-- 在UserMaapper.xml 中,resultType 可以直接写接口名称,且不区分大小写了-->
        <typeAliases>
            <package name="com.zxx.pojo"/>
        </typeAliases>
        
        <!--
        environments:配置数据库连接信息,可以配置多个environment,通过default属性来切换不同的environment
        -->
        <environments default="develop">
            <environment id="develop">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <!-- 连接信息 -->
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://127.0.0.1:13306/myatis_demo?serverTimezone=UTC"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
    
            <environment id="test">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <!-- 连接信息 -->
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://127.0.0.1:13306/myatis_demo?serverTimezone=UTC"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
    
        <mappers>
            <!--加载sql映射文件-->
            <!--<mapper resource="com/zxx/mapper/UserMapper.xml"/>-->
    
            <!-- 如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载-->
            <package name="com.zxx.mapper"/>
        </mappers>
    </configuration>
    
  4. 编写SQL映射文件 --> 统一管理SQL语句,解决硬编码问题

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--
        namespace:名称空间
    -->
    <mapper namespace="test">
        <select id="selectAllUser" resultType="com.zxx.pojo.User">
            select * from user;
        </select>
    
    </mapper>
    
  5. 编码

    1. 定义POJO类

      package com.zxx.pojo;
      
      public class User {
          private String name;
          private String password;
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public String getPassword() {
              return password;
          }
      
          public void setPassword(String password) {
              this.password = password;
          }
      
          @Override
          public String toString() {
              return "User{" +
                      "name='" + name + '\'' +
                      ", password='" + password + '\'' +
                      '}';
          }
      }
      
    2. 加载核心配置文件,获取SqlSessionFactory对象

    3. 获取SqlSession对象,执行SQL语句

    4. 释放资源

      package com.zxx;
      
      import com.zxx.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.InputStream;
      import java.util.List;
      
      /*
       * MyBatis快速入门
       */
      public class MyBatis {
          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 = sqlSession.selectList("test.selectAllUser");
      
              System.out.println(users);
      
              //4.释放资源
              sqlSession.close();
          }
      }
      

Mapper代理开发

  1. 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL的映射文件放到同一个路径下,可以在Resources路径下创建与接口路径相同的结构,需要用 / 分隔,编译后会在同一个目录下

  2. 设置SQL映射文件的namespace属性为Mapper接口全限定名

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

    package com.zxx.mapper;
    
    import com.zxx.pojo.User;
    
    import java.util.List;
    
    public interface UserMapper {
        List<User> selectAllUser();
    }
    
  4. 编码

    package com.zxx;
    
    import com.zxx.mapper.UserMapper;
    import com.zxx.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.InputStream;
    import java.util.List;
    
    /*
     * MyBatis代理开发
     */
    public class MyBatis2 {
        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
            // 3.1 获取UserMapper接口的代理对象
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = userMapper.selectAllUser();
    
            System.out.println(users);
    
            //4.释放资源
            sqlSession.close();
        }
    }
    

配置文件完成增删改查

安装MyBatisX插件

  1. 查询
    • 查询所有数据
      • 编写接口方法
      • 编写SQL语句
      • 执行方法
    • 查看详情
    • 条件查询
  2. 添加
  3. 修改
    • 修改全部字段
    • 修改动态字段
  4. 删除
    • 删除一个
    • 批量删除
实体类
package com.zxx.pojo;

public class Brand {
    private Integer id;
    private String brandName;
    private String companyName;
    private Integer ordered;
    private String description;
    private Integer status;

    public Integer getId() {
        return id;
    }

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

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}

Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
    namespace:名称空间
-->
<mapper namespace="com.zxx.mapper.BrandMapper">

    <!--
        数据库表的字段名称和实体类的属性名称不一样,则不能自动封装
        解决方案:
            1.可以手动给查询出来的字段 起别名(太麻烦)
            2.使用sql片段(不灵活)
            3.resultMap,自动映射
    -->

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



    <!--
        resultMap
        id:唯一标识
        type:映射的类型
    -->
    <resultMap id="brandResultMap" type="com.zxx.pojo.Brand">
        <!--
            id:主键字段的映射
            result:一般字段的映射
                column:表的列名
                property:实体类的属性名
        -->
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>


    <!--statement
    <select id="selectAll" resultType="com.zxx.pojo.Brand">
        &lt;!&ndash;select * from tb_brand;&ndash;&gt;
        select *
        from tb_brand;
    </select>-->

    <!--statement-->
    <select id="selectAll" resultMap="brandResultMap">
        select *
        from tb_brand;
    </select>

    <!--
        参数占位符
        1.#{}:会替换为 ? ,为了防止SQL注入
        2.${}:直接拼SQL,会存在SQL注入问题
        3.使用时机:
            参数传递: #{}
            动态查询:表名或者列名称不固定的情况下

        参数类型:parameterType 可以省略
        特殊字符的处理:
            1.转义字符
            2.CDATA区
                select *
                from tb_brand
                where id
                <![CDATA[
                    <
                ]]>
                ${id};
    -->
    <select id="selectById" parameterType="int" resultMap="brandResultMap">
        select *
        from tb_brand
        where id = ${id};
    </select>


    <select id="selectByCondition1" resultMap="brandResultMap">
        select *
        from tb_brand
        where status = #{status}
        and company_name like #{companyName}
        and brand_name like #{brandName}
    </select>

    <select id="selectByCondition2" resultMap="brandResultMap">
        select *
        from tb_brand
        where status = #{status}
        and company_name like #{companyName}
        and brand_name like #{brandName}
    </select>

    <!--    <select id="selectByCondition3" resultMap="brandResultMap">-->
    <!--        select *-->
    <!--        from tb_brand-->
    <!--        where status = #{status}-->
    <!--        and company_name like #{companyName}-->
    <!--        and brand_name like #{brandName}-->
    <!--    </select>-->

    <!--
        动态条件查询
        if 标签:完成对应条件的判断
        解决方案:
            1.在where后面 写 1=1(恒等式)
            2.使用MyBtis自带的<where>标签,帮我们判断
    -->
    <select id="selectByCondition3" resultMap="brandResultMap">
        select *
        from tb_brand
        <!-- <if test="status != null or companyName != null and companyName != '' or brandName != null and brandName != ''">
             where 1 = 1
         </if>-->
        <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><!--相当于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>

    <!--
        useGeneratedKeys="true" keyProperty="id"
        可以完成添加后返回主键的功能
    -->
    <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>

    <update id="updateByCondition">
        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>

    <!--
        根据id单条删除
    -->
    <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(
            <!--
                separator="," 用逗号分割 open="(" close=")":可以不用手写括号了
                collection:默认是array,但是使用了@Param注解,所以可以用ids
            -->
            <foreach collection="ids" item = "id" separator="," >
                #{id}
            </foreach>
         )

    </delete>

</mapper>
Mapper接口
package com.zxx.mapper;

import com.zxx.pojo.Brand;
import org.apache.ibatis.annotations.Param;

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

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

    /*
    * 查看详情
    */
    Brand selectById(Integer id);

    /*
    * 多条件动态查询: 散装参数
    */
    List<Brand> selectByCondition1(@Param("status") int status,@Param("companyName") String companyName,@Param("brandName") String brandName);

    /*
     * 多条件动态查询: 对象参数,对象属性的名称要和参数占位符名称一致
     */
    List<Brand> selectByCondition2(Brand brand);

    /*
     * 多条件动态查询:map参数
     */
    List<Brand> selectByCondition3(Map map);

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

    /*
    *  添加一个对象
    * */
    void add(Brand brand);

    /*
    * 修改全部字段
    * */
    int update(Brand brand);

    /*
     * 动态修改字段
     * */
    int updateByCondition(Brand brand);

    /*
    * 根据Id删除
    * */
    void deleteById(Integer id);

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

测试类
package com.zxx.mapper;

import com.zxx.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.HashMap;
import java.util.List;
import java.util.Map;

public class MyBatis_Test {

    @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对象,用它来执行SQL
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        List<Brand> brands = brandMapper.selectAll();
        System.out.println(brands);

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

    @Test
    public void testSelectById() 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.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        Brand brands = brandMapper.selectById(2);
        System.out.println(brands);

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

    @Test
    public void testSelectByCondition1() 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.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        List<Brand> brands = brandMapper.selectByCondition1(1, "%华为%", "%华为%");
        System.out.println(brands);

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

    @Test
    public void testSelectByCondition2() throws IOException {

        Brand brand = new Brand();
        brand.setStatus(1);
        brand.setCompanyName("%华为%");
        brand.setBrandName("%华为%");

        //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.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        List<Brand> brands = brandMapper.selectByCondition2(brand);
        System.out.println(brands);

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

    @Test
    public void testSelectByCondition3() throws IOException {
        Map map = new HashMap<>();
        map.put("status", 1);
        //map.put("companyName","%华为%");
        // map.put("brandName","%华为%");
        //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.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        List<Brand> brands = brandMapper.selectByCondition3(map);
        System.out.println(brands);

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

    @Test
    public void testSelectByConditionSingle() throws IOException {
        Brand brand = new Brand();
        //brand.setStatus(1);
        //brand.setCompanyName("%华为%");
        brand.setBrandName("%华为%");

        //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.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        List<Brand> brands = brandMapper.selectByConditionSingle(brand);
        System.out.println(brands);

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

    @Test
    public void testAdd() throws IOException {
        Brand brand = new Brand();
        brand.setStatus(1);
        brand.setCompanyName("波导手机");
        brand.setBrandName("波导");
        brand.setDescription("手机中的战斗机");
        brand.setOrdered(100);

        //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();
        //自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        brandMapper.add(brand);

        /*//5.手动提交事务
        sqlSession.commit();*/

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

    @Test
    public void testAdd2() throws IOException {
        Brand brand = new Brand();
        brand.setStatus(1);
        brand.setCompanyName("波导手机");
        brand.setBrandName("波导");
        brand.setDescription("手机中的战斗机");
        brand.setOrdered(100);

        //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();
        //自动提交事务
        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);

        /*//5.手动提交事务
        sqlSession.commit();*/

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

    @Test
    public void testUpdate() throws IOException {
        Brand brand = new Brand();
        brand.setStatus(1);
        brand.setCompanyName("波导手机");
        brand.setBrandName("波导");
        brand.setDescription("波导手机,手机中的战斗机");
        brand.setOrdered(200);
        brand.setId(8);

        //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();
        //自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        brandMapper.update(brand);
        //释放资源
        sqlSession.close();
    }

    @Test
    public void testupdateByCondition() throws IOException {
        Brand brand = new Brand();
        brand.setStatus(4);
        // brand.setCompanyName("波导手机");
        //brand.setBrandName("波导");
        //brand.setDescription("波导手机,手机中的战斗机");
        //brand.setOrdered(200);
        brand.setId(7);

        //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();
        //自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        brandMapper.updateByCondition(brand);
        //释放资源
        sqlSession.close();
    }

    @Test
    public void testDeleteById() 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();
        //自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        brandMapper.deleteById(7);

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

    @Test
    public void testDeleteByIds() throws IOException {
        int[] ids = new int[]{5,6};

        //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();
        //自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法
        brandMapper.deleteByIds(ids);

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

注解完成增删改查

直接在接口上添加注解 并完成SQL
package com.zxx.mapper;

import com.zxx.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {
    List<User> selectAllUser();

    User select(@Param("name") String username, @Param("password") String password);

    @Select("select * from user where id=#{id}")
    User selectUserById(int id);

}
测试类
package com.zxx.mapper;

import com.zxx.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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class MyBatis_Test2 {

    @Test
    public void testUserSelect() 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();
        //自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = userMapper.select("'zxx'","'zxxpass'");
        System.out.println(user);
    }

    @Test
    public void testUserSelectUserById() 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();
        //自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = userMapper.selectUserById(1);
        System.out.println(user);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迪迦敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值