MyBatis完成增删改查案例(详细代码)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 RDS MySQL Serverless,价值2615元额度,1个月
简介: MyBatis完成增删改查案例(详细代码)

🍁查询

🔥解决属性名和字段名不一致的问题

数据库表的字段名和实体类的属性名不一致,则不能自动封装数据。

  • 1.起别名
    缺点:每次查询都要定义一次别名

    • 2.sql片段
      缺点:不灵活
    • 3.resultMap

       1.定义resultMap标签
       2.在select标签中,使用resultMap属性替换resultType替换。
<!-- 1.起别名-->
   <!-- <select id="selectAll" resultType="brand">
       select id,brand_name as brandName,company_name as companyName,ordered,description,status
       from tb_brand;
    </select>-->

    <!--2.sql片段-->
    <!--<sql id="sql">
         id,brand_name as brandName,company_name as companyName,ordered,description,status
    </sql>
    <select id="selectAll" resultType="brand">
        select <include refid="sql"/>
        from tb_brand;
    </select>-->

   <!-- 3.resultMap-->
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>
    <select id="selectAll" resultMap="brandResultMap">
        select * from tb_brand;
    </select>

🔥模糊查询

  • java代码执行的时候,传递通配符% %
 //接收参数
        int status=1;
        String companyName="华为";
        String brandName="华为";
       //处理参数
        companyName="%"+companyName+"%";
        brandName="%"+brandName+"%";
  • 在sql拼接中使用通配符!
<select id="selectByCondition" resultMap="brandResultMap">
        select * from tb_brand
        where status =#{status}
        and company_name like "%"#{companyName}"%"
        and brand_name like "%"#{brandName}"%"
        ;

    </select>

🔥特殊字符处理

在通过id查询数据时,查询条件是id小于某个数时。

  • 转义字符
  • CDATA区
select * from tb_brand
         where id
         <![CDATA[
         <
         ]]>
         #{id};

🔥参数占位符

  • ${}:拼sql,存在sql注入问题
  • {}:会将其替换为?,防止sql注入

🔥参数接收

  • 1,散装参数:如果方法中有多个参数,需要使用@param("sql参数占位符名称")
List<Brand> selectByCondition(@Param("status") int status,@Param("companyName") String companyName,@Param("brandName") String brandName);
  • 2.实体类封装参数
List<Brand> selectByCondition(Brand brand);
  • 3.Map集合
 List<Brand> selectByCondition(Map map);

🔥动态条件查询

状态,公司名称,品牌名称,任意一个就可以查询数据

  • 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>
  • 2. 替换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>

🔥单条件动态条件查询

<!--<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>
            &lt;!&ndash;一个都没有选择&ndash;&gt;
            <otherwise>
                1=1
            </otherwise>
        </choose>
    </select>-->


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

🍁添加

🔥添加全部数据

<insert id="add" >
    insert into tb_brand(brand_name,company_name,ordered,description,status)
    values (#{brandName},#{companyName},#{ordered},#{description},#{status});
    </insert>

🔥返回添加数据的主键

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

🍁修改

🔥修改全部数据

根据id修改全部数据:

<update id="update">
        update tb_brand set  brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status}
        where id=#{id};
    </update>

🔥修改动态字段

根据id修改可以修改任意个字段:

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

🍁删除

🔥通过id删除数据

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

🔥通过id进行批量删除

mybatis会将数组参数,封装成一个Map集合

1.默认:array=数组
2.使用@param注解改变map集合的默认key的名称
<delete id="deleteByIds">
        delete from tb_brand where id
        in
            <foreach collection="ids" item="id" separator="," open="(" close=")">
            <!--<foreach collection="array" item="id" separator="," open="(" close=")">-->
                #{id}
            </foreach>
            ;
    </delete>

🍁MyBatis事务

 注意**增删改需要提交事务!**
  1. openSession():默认开启事务,进行增删改操作后,需要使用sqlSession.commit(); 手动提交事务。
//4.提交事务
        sqlSession.commit();

2.openSession(true);可以设置为自动提交事务和关闭事务。

 SqlSession sqlSession = sqlSessionFactory.openSession(true);

🍁增删改查案例分析

🔥数据库

创建数据库:mybatis
设计表:
在这里插入图片描述
往表里添加数据。

🔥pom.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.jkj</groupId>
    <artifactId>maven-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--import dependencies-->
    <dependencies>
        <!--mysql driver-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>

🔥brand实体类:

package com.jkj.pojo;

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

    public Brand() {
    }

    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = 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 +
                '}';
    }
}

🔥BrandMapper:

package com.jkj.Mapper;

import com.jkj.pojo.Brand;
import com.jkj.pojo.User;
import org.apache.ibatis.annotations.Param;

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

public interface BrandMapper {
   //查询所有
   List<Brand> selectAll();
   //查询详情,通过id查询
   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 map);
   //单条件动态条件查询
   List<Brand> selectByConditionSingle(Brand brand);

   //添加
   void add(Brand brand);
   //修改全部字段
   int update(Brand brand);
   //通过id删除数据
   void deleteById(int id);
   //批量删除
   void deleteByIds(@Param("ids") int[] ids);


}

🔥mybatis-config.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 core file-->
<configuration>
    <!--起别名,不区分大小写-->
    <typeAliases>
        <package name="com.jkj.pojo"/>
    </typeAliases>
    <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://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--加载sql映射文件-->
    <mappers>
        <!--<mapper resource="com/jkj/Mapper/UserMapper.xml"/>-->
        <!--Mapper代理方式-->
        <package name="com.jkj.Mapper"/>
    </mappers>
</configuration>

🔥BrandMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jkj.Mapper.BrandMapper">
    <!--
    数据库表的字段名和实体类的属性名不一致,则不能自动封装数据
    1.起别名
    缺点:每次查询都要定义一次别名
    2.sql片段
    缺点:不灵活
    3.resultMap
       1.定义resultMap标签
       2.在select标签中,使用resultMap属性替换resultType替换
    -->
    <!--<select id="selectAll" resultType="com.jkj.pojo.Brand">
         sel快捷键
        select * from tb_brand;
    </select>-->

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

    <!--2.sql片段-->
    <!--<sql id="sql">
         id,brand_name as brandName,company_name as companyName,ordered,description,status
    </sql>
    <select id="selectAll" resultType="brand">
        select <include refid="sql"/>
        from tb_brand;
    </select>-->

   <!-- 3.resultMap-->
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>
    <select id="selectAll" resultMap="brandResultMap">
        select * from tb_brand;
    </select>
    <!--通过id查询-->
    <!--
    参数占位符
    ${}:拼sql,存在sql注入问题
    #{}:会将其替换为?,防止sql注入
    -->
    <!--<select id="selectById" resultMap="brandResultMap">
        select * from tb_brand where id=#{id};

    </select>-->

    <!--特殊字符处理
    1.转义字符
    2.CDATA区
    -->
    <select id="selectById" resultMap="brandResultMap">
        select * from tb_brand
         where id
         <![CDATA[
         <
         ]]>
         #{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>-->
    <!--动态条件查询-->
    <!--状态,公司名称,品牌名称,任意一个就可以查询数据
    -->
   <!-- 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>-->

  <!--  2.<where> 替换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>
    <!--单条件动态查询-->
    <!--<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>
            &lt;!&ndash;一个都没有选择&ndash;&gt;
            <otherwise>
                1=1
            </otherwise>
        </choose>
    </select>-->
    <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>

    <!--添加数据-->
    <!--<insert id="add" >
    insert into tb_brand(brand_name,company_name,ordered,description,status)
    values (#{brandName},#{companyName},#{ordered},#{description},#{status});
    </insert>-->

    <!--返回添加数据的主键-->
    <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="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>
    <!--通过id删除数据-->
    <delete id="deleteById">
        delete from tb_brand where id=#{id};
    </delete>

    <!--批量删除-->
    <!--
    mybatis会将数组参数,封装成一个Map集合
    1.默认:array=数组
    2.使用@param注解改变map集合的默认key的名称
    -->
    <delete id="deleteByIds">
        delete from tb_brand where id
        in
            <foreach collection="ids" item="id" separator="," open="(" close=")">
            <!--<foreach collection="array" item="id" separator="," open="(" close=")">-->
                #{id}
            </foreach>
            ;
    </delete>


</mapper>

🔥测试类:

package com.jkj.test;

import com.jkj.Mapper.BrandMapper;
import com.jkj.Mapper.UserMapper;
import com.jkj.pojo.Brand;
import com.jkj.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;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyBatisTest {
    @Test
    public void selectAll() 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();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        List<Brand> brands = mapper.selectAll();
        System.out.println(brands);
        //4.释放资源
        sqlSession.close();

       /* [Brand{id=1, brandName='华为', companyName='华为有限技术公司', ordered=100, description='华为牛逼', status=1},
       Brand{id=2, brandName='小米', companyName='小米有限技术公司', ordered=50, description='小米不孬', status=1},
       Brand{id=3, brandName='荣耀', companyName='荣耀有限技术公司', ordered=20, description='荣耀很中', status=1}]*/
    }
    @Test
    public void selectById() 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();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        Brand brand = mapper.selectById(2);
        System.out.println(brand);
        //4.释放资源
        sqlSession.close();
        /*Brand{id=1, brandName='华为', companyName='华为有限技术公司', ordered=100, description='华为牛逼', status=1}*/
    }
    @Test
    public void selectByCondition() 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 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,执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        //List<Brand> brands = mapper.selectByCondition(status, companyName, brandName);
        //List<Brand> brands = mapper.selectByCondition(brand);
        List<Brand> brands = mapper.selectByCondition(map);
        System.out.println(brands);
        //4.释放资源
        sqlSession.close();
        /*[Brand{id=1, brandName='华为', companyName='华为有限技术公司', ordered=100, description='华为牛逼', status=1}]*/

    }
    @Test
    public void selectByConditionSingle() 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,执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        List<Brand> brands = mapper.selectByConditionSingle(brand);
        System.out.println(brands);
        //4.释放资源
        sqlSession.close();
    }
    @Test
    public void add() throws IOException {
        //接收参数
        int status=0;
        String companyName="今麦郎";
        String brandName="今麦郎";
        int ordered=200;
        String description="今麦郎可以";
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        //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();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        mapper.add(brand);
        //4.提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
    @Test
    public void add2() throws IOException {
        //接收参数
        int status=1;
        String companyName="农夫山泉";
        String brandName="农夫山泉";
        int ordered=200;
        String description="农夫山泉真甜";
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        //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();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        mapper.add(brand);
        //获取添加数据的主键
        Integer id = brand.getId();
        System.out.println(id);  //6
        //4.提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
    @Test
    public void TestUpdate() throws IOException {
        //接收参数
        int status=1;
        String companyName="农夫山泉plus";
        String brandName="农夫山泉plus";
        int ordered=200;
        String description="农夫山泉甜甜甜";
        int id=5;
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        brand.setId(id);
        //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(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        int count = mapper.update(brand);
        System.out.println(count); //受影响的行数
        //4.提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
    @Test
    public void TestUpdate1() throws IOException {
        //接收参数
        int status=1;
        String companyName="农夫山泉plus";
        String brandName="农夫山泉plus";
        int ordered=200;
        String description="我只是大自然的搬运工";
        int id=5;
        //封装对象
        Brand brand = new Brand();
       /* brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setOrdered(ordered);*/
        brand.setDescription(description);
        brand.setId(id);
        //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(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        int count = mapper.update(brand);
        System.out.println(count); //受影响的行数
        //4.提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
    @Test
    public void TestDeleteById() throws IOException {

        int id=5;
        //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(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        mapper.deleteById(id);
        //4.提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
    @Test
    public void TestDeleteByIds() throws IOException {

        int [] ids={4,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(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行sql
        mapper.deleteByIds(ids);
        //4.提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
    @Test
    public void TestSelectAll() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取sqlSession,执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = (UserMapper) sqlSession.getMapper(UserMapper.class);
        //3.执行sql
        List<User> users = mapper.selectAll();
        System.out.println(users);
        //4.释放资源
        sqlSession.close();
//[User{id=1, username='小马哥', password='111', gender='男', addr='北京'},
// User{id=2, username='小飞侠', password='222', gender='男', addr='上海'},
// User{id=3, username='马奎斯', password='333', gender='女', addr='西班牙'}]

    }
}
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1月前
Mybatis+mysql动态分页查询数据案例——测试类HouseDaoMybatisImplTest)
Mybatis+mysql动态分页查询数据案例——测试类HouseDaoMybatisImplTest)
22 1
|
1月前
|
Java 关系型数据库 数据库连接
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
30 1
|
1月前
|
XML Java 数据库连接
mybatis环境搭建步骤(含配置文件代码)
mybatis环境搭建步骤(含配置文件代码)
15 1
|
1月前
Mybatis+mysql动态分页查询数据案例——条件类(HouseCondition)
Mybatis+mysql动态分页查询数据案例——条件类(HouseCondition)
16 1
|
1月前
Mybatis+mysql动态分页查询数据案例——分页工具类(Page.java)
Mybatis+mysql动态分页查询数据案例——分页工具类(Page.java)
24 1
|
1月前
Mybatis+mysql动态分页查询数据案例——房屋信息的实现类(HouseDaoMybatisImpl)
Mybatis+mysql动态分页查询数据案例——房屋信息的实现类(HouseDaoMybatisImpl)
22 2
|
1月前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
26 0
|
1月前
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
16 1
|
1月前
|
Java 数据库连接 mybatis
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
20 1
|
1月前
Mybatis+mysql动态分页查询数据案例——配置映射文件(HouseDaoMapper.xml)
Mybatis+mysql动态分页查询数据案例——配置映射文件(HouseDaoMapper.xml)
15 1