Mybatis case - addition, deletion, modification and query of commodities


JDBC completed: https://blog.csdn.net/meini32/article/details/131981238

1. aim

List of functions to be completed Checklist:
1. Query

  • query all data
  • check the details
  • conditional query

2. Add
3. Modify

  • Modify all fields
  • Modify dynamic fields

4. delete

  • delete one
  • batch deletion

2. Environment preparation

  1. Database table tb_brand
  2. Entity class Brand
  3. test case
  4. Install the MyBatis×plugin

Database Table:

-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
    -- id 主键
    id           int primary key auto_increment,
    -- 品牌名称
    brand_name   varchar(20),
    -- 企业名称
    company_name varchar(20),
    -- 排序字段
    ordered      int,
    -- 描述信息
    description  varchar(100),
    -- 状态:0:禁用  1:启用
    status       int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);


SELECT * FROM tb_brand;

Entity Brand class

package com.itheima.pojo;

public class Brand {
    
    
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    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 +
                '}';
    }
}

test case

insert image description here
MybatisX plugin

Function

  • XML and interface methods jump to each other
  • Generate statement based on interface method

insert image description here
insert image description here

3. Query

step

  • Write interface: Mapper interface
  • Write sql statement: sql mapping file
  • execute method, test

3.1 Check all

insert image description here
insert image description here
insert image description here
Note: The field name of the database table is different from the attribute name of the entity class, so the data cannot be automatically encapsulated

Method 1: Aliasing
insert image description here
insert image description here
Method 2: Mapping

1. Define the label
2. In the tag, replace the resultType attribute with the resultMap attribute

insert image description here

3.2 View details

View the details of a piece of data

1. Write mapper interface
insert image description here

2. Define accepting parameters
insert image description here

3. Write sql statement

<select id="selectById" resultMap="brandResultMap">
        select * from tb_brand where id = #{
    
    id};
    </select>

4. execute sql
insert image description here

Parameter placeholder
1. #{}: It will be replaced by?, in order to prevent SQL injection 2. ${}: spell sql. There will be SQL injection problems

3.3 Condition query

3.3.1 How does Mybatics receive parameters?

1. A single parameter

Parameters can be passed directly as method parameters. The parameter can be referenced in the form of #{paramName} in the SQL statement.

// Java 代码
public interface UserMapper {
    
    
    User getUserById(int id);
}

<!-- Mapper XML -->
<select id="getUserById" resultType="User">
    SELECT * FROM user WHERE id = #{
    
    id}
</select>

2. Use the @Param annotation to specify the name of the parameter:

You can use the @Param annotation to specify the name of the parameter, and then refer to the parameter by that name in the SQL statement.

// Java 代码
public interface UserMapper {
    
    
    User getUserByIdAndName(@Param("id") int id, @Param("name") String name);
}

<!-- Mapper XML -->
<select id="getUserByIdAndName" resultType="User">
    SELECT * FROM user WHERE id = #{
    
    id} AND name = #{
    
    name}
</select>

3. Use Map to pass parameters:

Multiple parameters can be passed using a parameter of type Map. Reference the corresponding value by key in the SQL statement:

// Java 代码
public interface UserMapper {
    
    
    User getUserByMap(Map<String, Object> params);
}

<!-- Mapper XML -->
<select id="getUserByMap" resultType="User">
    SELECT * FROM user WHERE id = #{
    
    id} AND name = #{
    
    name}
</select>

4. Use the object to pass parameters:

You can use a custom object as a parameter, and MyBatis will automatically map the properties of the object with the parameters in the SQL statement. For example:

// Java 代码
public class UserQuery {
    
    
    private int id;
    private String name;
    // 省略 getter 和 setter 方法
}

public interface UserMapper {
    
    
    User getUserByQuery(UserQuery query);
}

<!-- Mapper XML -->
<select id="getUserByQuery" resultType="User">
    SELECT * FROM user WHERE id = #{
    
    id} AND name = #{
    
    name}
</select>
3.3.2 Multi-condition query

step

  1. Write the interface (mapper) for multi-condition query;
  2. added to the mapping file
  3. Write sql statement
  4. execute, test

1. Define the interface

public interface BrandMapper {
    
    
    List<Brand> selectAll();
    Brand selectById(int id);  //通过id查看商品详情

    //使用 @Param 注解来指定参数的名称
    List<Brand> selectByMutiCondition(@Param("status")int status,@Param("companyName")String companyName,@Param("brandName")String brandName);
    
    //使用对象来指定参数
    List<Brand> selectByMutiCondition(Brand brand);  

   //使用map来指定参数
    List<Brand> selectByMutiCondition(HashMap map);
    

}

2. Add to the mapping file

<!--
namespace:名称空间
-->

<mapper namespace="com.itheima.mapper.BrandMapper">

    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>

<!--    多条件查询-->
    <select id="selectByMutiCondition" resultMap="brandResultMap">
        SELECT * FROM tb_brand
        WHERE status = #{status} AND company_name LIKE #{companyName} AND brand_name LIKE #{brandName};
    </select>

</mapper>

3. Execute, test

//多条件查询-使用参数查询
public class MyBatisTest3 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        int s = 0;
        String cn = "三只松鼠股份有限公司";
        String bn = "三只松鼠";

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brand = brandMapper.selectByMutiCondition(s,cn,bn);

        System.out.println(brand);

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


//多条件查询-使用对象
public class MyBatisTest3 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        int s = 0;
        String cn = "三只松鼠股份有限公司";
        String bn = "三只松鼠";

        Brand brand1 = new Brand();
        brand1.setStatus(s);
        brand1.setBrandName(bn);
        brand1.setCompanyName(cn);

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brand = brandMapper.selectByMutiCondition(brand1);

        System.out.println(brand);

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


//多条件查询-使用Map
public class MyBatisTest3 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        int s = 0;
        String cn = "三只松鼠股份有限公司";
        String bn = "三只松鼠";

        HashMap map = new HashMap();
        map.put("status",s);
        map.put("companyName",cn);
        map.put("brandName",bn);

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brand = brandMapper.selectByMutiCondition(map);

        System.out.println(brand);

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

result:insert image description here

3.3.3 Dynamic Condition Query

Dynamic conditional query refers to constructing dynamic SQL query statements according to different conditional combinations.
method

  • Use the <if element
  • Use <choose, <when, <otherwise elements:
  • Use <trim, <where, <set elements
使用if
<select id="getUserByCondition" resultType="User">
    SELECT * FROM user
    WHERE 1=1
    <if test="id != null">
        AND id = #{id}
    </if>
    <if test="name != null">
        AND name = #{name}
    </if>
</select>
使用 choose, when, otherwise 元素
<select id="getUserByCondition" resultType="User">
    SELECT * FROM user
    WHERE 1=1
    <choose>
        <when test="id != null">
            AND id = #{id}
        </when>
        <when test="name != null">
            AND name = #{name}
        </when>
        <otherwise>
            AND status = 'ACTIVE'
        </otherwise>
    </choose>
</select>
使用 trim, where, set元素
<update id="updateUser" parameterType="User">
    UPDATE user
    <set>
        <if test="name != null">
            name = #{
    
    name},
        </if>
        <if test="age != null">
            age = #{
    
    age},
        </if>
    </set>
    WHERE id = #{
    
    id}
</update>

1. Write the interface

List<Brand> selectByMutiConditionActivate(Brand brand);

2. Write a dynamic query mapping file

<!--    动态查询-->
    <select id="selectByMutiConditionActivate" 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>

3. 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 java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

public class MyBatisTest4 {
    
    
    public static void main(String[] args) throws IOException {
    
    
//        int s = 1;
        String cn = "三只松鼠股份有限公司";
//        String bn = "三只松鼠";

        Brand brand1 = new Brand();
//        brand1.setStatus(s);
//        brand1.setBrandName(bn);
        brand1.setCompanyName(cn);

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brand = brandMapper.selectByMutiConditionActivate(brand1);

        System.out.println(brand);

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

4. Results
insert image description here

3.3.4 Single condition query

MyBatis single-condition dynamic query refers to dynamically constructing SQL
query statements based on the existence or non-existence of a single condition. According to different condition values, choose whether to add the condition to the query statement, so as to realize the function of flexible query based on a single condition.
Use <choose, "when> and "otherwise> elements to implement conditional selection logic, and select one of the branches for processing according to different conditions

<select id="getUserByCondition" resultType="User">
  SELECT * FROM user
  WHERE 1=1
  <choose>
    <when test="name != null">
      AND name = #{name}
    </when>
    <when test="age != null">
      AND age = #{age}
    </when>
    <otherwise>
      AND 1=1
    </otherwise>
  </choose>
</select>

4. Add

insert image description here

step

  1. Write interface methods
  2. Write sql statement, add mapping file
  3. execute method, test

MyBatis transaction:

  • openSession(): The transaction is enabled by default, and you need to use sqlSession.commit() after adding, deleting, and modifying operations;
  • Manually commit the transaction openSession(true): Can be set to automatically commit the transaction (close the transaction)

1. Write the interface

public interface BrandMapper {
    
    
    
    //添加
    void addBrand(Brand brand);
}

2. Edit the mapping file

<!--
namespace:名称空间
-->

<mapper namespace="com.itheima.mapper.BrandMapper">

    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>

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

</mapper>

3. Test results


//添加
public class MybatisTest5 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        String bn = "百度";
        String cn = "百度公司";
        int od = 18;
        String ds = "百度一下你就知道";
        int st =0;

        Brand brand = new Brand();
        brand.setBrandName(bn);
        brand.setStatus(st);
        brand.setCompanyName(cn);
        brand.setDescription(ds);
        brand.setOrdered(od);

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.addBrand(brand);

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

        //5.关闭
        sqlSession.close();

    }
}

insert image description here

primary key returns

what is it

After the data is added successfully, you need to obtain the value of the primary key inserted into the database.
For example: Adding an order and order item
1. Adding an order
2. Adding an order item. The id of the order to which it belongs needs to be set in the order item

insert image description here
insert image description here

Reason: The id is not bound to the object after execution

Solution: MyBatis framework can use useGeneratedKeys and keyProperty
attributes to automatically obtain the generated primary key value and set it to the corresponding attribute.

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

insert image description here

5. Modify

sql statement

UPDATE 表名 SET 列名1=1,列名2=2,... [ WHERE 条件];

mybatis tag

<update id="updateOrder" parameterType="Order">
  UPDATE orders
  SET order_number = #{orderNumber}, order_date = #{orderDate}
  WHERE id = #{id}
</update>

5.1 Modify all fields

public interface BrandMapper {
    
    
    //修改
    void updateBrand(Brand brand);
}

<update id="updateBrand">
        update tb_brand
        set brand_name=#{brandName},
            company_name=#{companyName},
            ordered=#{ordered},
            description=#{description},
            status=#{status}
        where id = #{id};
    </update>
//返回修改全部字段
public class MybatisTest7 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        String bn = "快手";
        String cn = "fasthand公司";
        int od = 666;
        String ds = "老铁加油哇";
        int st =1;
        int id = 7;

        Brand brand = new Brand();
        brand.setId(id);
        brand.setBrandName(bn);
        brand.setStatus(st);
        brand.setCompanyName(cn);
        brand.setDescription(ds);
        brand.setOrdered(od);

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.updateBrand(brand);


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

        //5.关闭
        sqlSession.close();

    }
}

insert image description here

5.2 Modify dynamic fields

In MyBatis, you can use elements to dynamically modify fields. The element determines whether to include a modification statement fragment of a field according to whether the condition is true or not.

void updateBrandActivate(Brand brand);
<update id="updateBrandActivate">
        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 and ordered!='' ">ordered=#{ordered}</if>
            <if test="description != null and description!='' ">description=#{description}</if>
            <if test="status != null and status!='' ">status=#{status}</if>
        </set>
        where id = #{id};
    </update>
//返回动态修改字段
public class MybatisTest8 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        String bn = "快手";
        String cn = "fasthand公司";
        int od = 666;
        String ds = "先穿裤子在穿鞋,先当孙子再当爷,记住这句话!";
        int st =0;
        int id = 7;

        Brand brand = new Brand();
        brand.setId(id);
//        brand.setBrandName(bn);
        brand.setStatus(st);
//        brand.setCompanyName(cn);
        brand.setDescription(ds);
//        brand.setOrdered(od);

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.updateBrandActivate(brand);


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

        //5.关闭
        sqlSession.close();

    }
}

insert image description here

6. Delete

sql statement

DELETE FROM 表名 [WHERE 条件] ;

6.1 Delete 1

void deleteOne(int id);
<delete id="deleteOne">
        delete from tb_brand where id = #{id};
    </delete>

//删除1

public class MybatisTest9 {
    
    
    public static void main(String[] args) throws IOException {
    
    

        int id = 6;

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.deleteOne(id);


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

        //5.关闭
        sqlSession.close();

    }
}

6.2 Batch delete

void deleteMuti(@Param("ids")int[] ids);
<delete id="deleteMuti">
        delete from tb_brand
        where id
        in(
        <foreach collection="ids" item="id" separator=",">
            #{id}
        </foreach>
        );
    </delete>

//删除1

public class MybatisTest9 {
    
    
    public static void main(String[] args) throws IOException {
    
    

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

        //1.加载核心文件,获取SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

        //3.执行sql
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.deleteMuti(ids);


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

        //5.关闭
        sqlSession.close();

    }
}

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/meini32/article/details/132095237