【MyBatis】| Use MyBatis to complete CRUD operations

Table of contents

One: Use MyBatis to complete CRUD

1. Mybatis completes the insert and uses the Map collection to pass parameters

2. Mybatis completes the insert and uses PoJo to pass parameters

3. MyBatis completes the delete operation

4. MyBatis completes the update operation

5. MyBatis completes the selection to check one

6. Mybatis completes select and checks all

7. The namespace of the SQL Mapper mapping file


One: Use MyBatis to complete CRUD

Preparation

(1) Create a module (Maven's normal Java module)

(2) Configure pom.xml

① Packaging method jar

②Introduction of dependencies: mybatis dependencies, mysql driver dependencies, junit dependencies, logback dependencies

(3) mybatis-config.xml is placed under the root path of the class

(4) CarMapper.xml is placed under the root path of the class

(5) logback.xml is placed under the root path of the class

(6) Provide com.bjpowernode.mybatis.utils.SqlSessionUtil tool class

(7) Create a test case: com.powernode.mybatis.CarMapperTest

<?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>mybatis-002-crud</groupId>
    <artifactId>com.bjpowernode</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--出现1.5的警报,就加上这两句话-->
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <!--打包方式jar-->
    <packaging>jar</packaging>
    <!--引入依赖-->
    <dependencies>
        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <!--mysql驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.23</version>
        </dependency>
        <!--加入单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--引入logback的依赖-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

1. Mybatis completes the insert and uses the Map collection to pass parameters

(1) What is CRUD, C: Create, R: Retrieve (retrieve), U: Update, D: Delete

(2) The original insert statement is hard-coded into the configuration file, which does not exist in actual development. The data must be submitted by the front-end form form, and then the value is passed to the SQL statement

<?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="first">
    <insert id="insertCar">
      insert into t_car(id,car_num,brand,guide_price,produce_time,car_type)
      values(null,'1003','丰田',30.0,'2000-10-11','燃油车');
    </insert>
</mapper>

(3) The placeholder in JDBC is ? , in mybatis it is #{} ; #{} is equivalent to ? in JDBC. And the value passed in this #{} is the key of the Map collection . If the key does not exist, it will get null!

(4) Test class

package com.bjpowernode.mybatis.test;

import com.powernode.mybatis.utils.SqlSessionUtils;
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.util.HashMap;
import java.util.Map;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.mybatis.test
 * @Project:mybatis
 * @name:CarMapperTest
 * @Date:2022/12/28 21:53
 */
public class CarMapperTest {
    @Test
    public void testInsertCarByUtil(){
        SqlSession sqlSession = SqlSessionUtils.openSession();

        // Map集合的数据
        Map<String, Object> map = new HashMap<>();
        map.put("carNum","1111");
        map.put("brand","比亚迪汉");
        map.put("guidePrice",10.0);
        map.put("produceTime","2022-11-11");
        map.put("carType","电车");
        // insert方法:一个参数是id,另一个参数是一个map集合
        int count = sqlSession.insert("insertCar",map);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

}

(5) sql statement

<?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="first">
    <insert id="insertCar">
      insert into t_car(id,car_num,brand,guide_price,produce_time,car_type)
      values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType});
    </insert>
</mapper>

2. Mybatis completes the insert and uses PoJo to pass parameters

(1) In addition to using the Map collection to pass values ​​to the placeholders of the SQL statement, it is also possible to use a PoJo class (ordinary java class)

Pojo type 

package com.powernode.mybatis.pojo;

/**
 * @Author:朗朗乾坤
 * @Package:com.powernode.mybatis.pojo
 * @Project:mybatis
 * @name:Car
 * @Date:2022/12/29 19:09
 * 封装汽车相关信息的pojo类,普通的java类
 */
public class Car {
    // 数据库表中的字段应该和pojo类的属性一一对应
    private Long id;
    private String carNum;
    private String brand;
    private Double guidePrice;
    private String produceTime;
    private String carType;
    // 构造方法
    public Car() {
    }
    public Car(Long id, String carNum, String brand, Double guidePrice, String produceTime, String carType) {
        this.id = id;
        this.carNum = carNum;
        this.brand = brand;
        this.guidePrice = guidePrice;
        this.produceTime = produceTime;
        this.carType = carType;
    }
    // setter  and getter
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    public String getCarNum() {
        return carNum;
    }
    public void setCarNum(String carNum) {
        this.carNum = carNum;
    }

    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Double getGuidePrice() {
        return guidePrice;
    }
    public void setGuidePrice(Double guidePrice) {
        this.guidePrice = guidePrice;
    }

    public String getProduceTime() {
        return produceTime;
    }
    public void setProduceTime(String produceTime) {
        this.produceTime = produceTime;
    }

    public String getCarType() {
        return carType;
    }
    public void setCarType(String carType) {
        this.carType = carType;
    }

    // toString方法
    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", carNum='" + carNum + '\'' +
                ", brand='" + brand + '\'' +
                ", guidePrice=" + guidePrice +
                ", produceTime='" + produceTime + '\'' +
                ", carType='" + carType + '\'' +
                '}';
    }
}

(2) Write a test class and directly pass a PoJo class that we encapsulated into it

package com.bjpowernode.mybatis.test;

import com.powernode.mybatis.pojo.Car;
import com.powernode.mybatis.utils.SqlSessionUtils;
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.util.HashMap;
import java.util.Map;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.mybatis.test
 * @Project:mybatis
 * @name:CarMapperTest
 * @Date:2022/12/28 21:53
 */
public class CarMapperTest {

    public void testInsertCarByPojo(){
        SqlSession sqlSession = SqlSessionUtils.openSession();
        // 使用Pojo类封装
        Car car = new Car(null,"333","比亚迪森",30.0,"2020-11-11","新能源");
        // 执行sql
        int count = sqlSession.insert("insertCar", car);
        System.out.println(count);

        sqlSession.commit();
        sqlSession.close();
    }

}

(3) The way of the Map collection to pass the value to the Sql statement is to pass the key of the Map collection, so how to use the PoJo class to pass the value? The passed value is the method name of the getXxx() method, remove get, then lowercase the first letter of the remaining word xxx, and then put it in; for example: getUsername() --> #{username}

<?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="first">
    <insert id="insertCar">
      insert into t_car(id,car_num,brand,guide_price,produce_time,car_type)
      <!--对应get方法所得到的参数-->
      values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType});
    </insert>
</mapper>

3. MyBatis completes the delete operation

(1) Write a deleted Sql statement

Note: If there is only one placeholder, the curly braces of #{} are free, but it is best to know the name.

<?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="first">
    <!--通过id删除-->
    <delete id="deleteById">
        <!--变量名随便写-->
        delete from t_car where id = #{id};
    </delete>
</mapper>

(2) Write the test method and test it

package com.bjpowernode.mybatis.test;

import com.powernode.mybatis.pojo.Car;
import com.powernode.mybatis.utils.SqlSessionUtils;
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.util.HashMap;
import java.util.Map;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.mybatis.test
 * @Project:mybatis
 * @name:CarMapperTest
 * @Date:2022/12/28 21:53
 */
public class CarMapperTest {
    @Test
    public void testDeleteById(){
        SqlSession sqlSession = SqlSessionUtils.openSession();
        // 执行sql,一个参数是id,另一个参数是要删除的id
        int count = sqlSession.delete("deleteById", 10);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

}

4. MyBatis completes the update operation

(1) Modify a record by id

Note: Using PoJo for data encapsulation is very similar to inserting data. For inserting data id, we pass null because it will be automatically generated; for update operations, we need to pass in the id, and then cover the data as a whole according to the id

(2) Write an updated Sql statement

<?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">
    <!--通过id更新-->
    <update id="updateById">
        update t_car set 
          car_num = #{carNum},
          brand = #{brand},
          guide_price = #{guidePrice},
          produce_time = #{produceTime},
          car_type = #{carType}
        where 
          id = #{id};
    </update>
</mapper>

(3) Write the test method and test it

package com.bjpowernode.mybatis.test;

import com.powernode.mybatis.pojo.Car;
import com.powernode.mybatis.utils.SqlSessionUtils;
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.util.HashMap;
import java.util.Map;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.mybatis.test
 * @Project:mybatis
 * @name:CarMapperTest
 * @Date:2022/12/28 21:53
 */
public class CarMapperTest {
    // 更新、修改
    @Test
    public void updateById(){
        SqlSession sqlSession = SqlSessionUtils.openSession();
        // 执行sql,根据传的id进行数据的覆盖修改
        Car car = new Car(4L,"9999","凯美瑞",30.3,"1999-11-10","燃油车");
        int count = sqlSession.update("updateById", car);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }
}

5. MyBatis completes the selection to check one

(1) Note: There is a resultType attribute in the select tag, which is used to tell mybatis what type of java object the query result set is encapsulated into.
The resultType is usually written: the fully qualified class name, with the package name.

<?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="first">
    <!--通过id查询,一个结果-->
    <select id="selectById" resultType="com.powernode.mybatis.pojo.Car">
        select * from t_car where id = #{id};
    </select>
</mapper>

(2) When writing the test code, the obtained result will actually be automatically encapsulated; the previous resultType attribute has specified the type as Car, so the returned type is actually a Car type

package com.bjpowernode.mybatis.test;

import com.powernode.mybatis.pojo.Car;
import com.powernode.mybatis.utils.SqlSessionUtils;
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.util.HashMap;
import java.util.Map;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.mybatis.test
 * @Project:mybatis
 * @name:CarMapperTest
 * @Date:2022/12/28 21:53
 */
public class CarMapperTest {
    // 查询一个
    @Test
    public void selectById(){
        SqlSession sqlSession = SqlSessionUtils.openSession();
        // 执行sql,这里会自动进行数据的封装
        // 前面已经指定了类型是Car,返回的类型实际上也是一个Car类型
        Object car = sqlSession.selectOne("selectById", 1);
        System.out.println(car instanceof Car); // true,返回的就是Car类型
        System.out.println(car);
        // DQL语句,不需要提交
        sqlSession.close();
    }

    
}

(3) Note: After testing, we found a strange phenomenon, only the id and brand fields have values, and the other fields are null; because other fields in the data are car_num, guide_price, produce_time, car_type and the encapsulated Car class carNum, guidePrice, produceTime , The carType field does not correspond, so there is no assignment!

(4) How to solve it? Use the as keyword to create a corresponding alias, and rewrite the sql statement; all are assigned normally!

Note: We can also configure aliases in the mybatis-config.xml core configuration file later, but certain conditions are required, which will be discussed later!

<?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="first">
    <!--通过id查询,一个结果-->
    <select id="selectById" resultType="com.powernode.mybatis.pojo.Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            id = #{id}
    </select>
</mapper>

6. Mybatis completes select and checks all

(1) Write sql statement, you don’t need to pass id to query all

Note: resultType still specifies the type of the result set to be encapsulated, not the specified List type, but the specified type of elements in the List collection; mybatis can know that you need a List collection through the selectList method; it will automatically return you a List gather!

<?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="first">
    <!--查询所有-->
    <select id="selectAll" resultType="com.powernode.mybatis.pojo.Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
    </select>
</mapper>

(2) It is not a simple object to check all the returned objects. Calling the selectList method returns a List collection; so it is enough to traverse and print this collection

package com.bjpowernode.mybatis.test;

import com.powernode.mybatis.pojo.Car;
import com.powernode.mybatis.utils.SqlSessionUtils;
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.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.mybatis.test
 * @Project:mybatis
 * @name:CarMapperTest
 * @Date:2022/12/28 21:53
 */
public class CarMapperTest {

    // 查询所有
    @Test
    public void selectAll(){
        SqlSession sqlSession = SqlSessionUtils.openSession();
        // 执行sql,返回的是一个List集合
        List<Object> list = sqlSession.selectList("selectAll");
        // 遍历输出
        for (Object car:list) {
            System.out.println(car);
        }
    }
}

7. The namespace of the SQL Mapper mapping file

(1) There is a namespace attribute in the XxxMapper.xml file, which is used to specify the namespace. Used to prevent id duplication!
(2) How to use it? For example: there are two CarMapper.xml and UserMapper.xml files that contain the same type of insert statement, and the statement contains the same id, and both files are referenced to the core file mybatis-config.xml; we write tests An error will occur if the program obtains the returned result through the id!

(3) So we can add the namespace attribute to prevent repeated id conflicts; so the correct syntax in the future should be: namespace.id, for example:

// first是namespace属性的值,selectAll是查询语句的id
List<Object> cars = sqlSession.selectList("first.selectAll");

Guess you like

Origin blog.csdn.net/m0_61933976/article/details/128482203