mybatis02 CRUD

CRUD代表四个基本功能:创建(Create)、检索(Retrieve)、更新(Update)和删除(Delete)。它们是大多数应用程序所需要的最基本的持久化操作。

- 创建(Create): 这是指创建或添加新的条目。
- 检索(Retrieve): 这是指读取或查看已有的条目。
- 更新(Update): 这是指更新或修改已有的条目。
- 删除(Delete): 这是指删除已有的条目。

pom.xml



    4.0.0

    com.wsd
    testMyBatis2
    1.0-SNAPSHOT
    jar

    
        
        
            org.mybatis
            mybatis
            3.5.10
        

        
        
            mysql
            mysql-connector-java
            8.0.30
        

        
        
            junit
            junit
            4.13.2
            test
        
        
        
        
            ch.qos.logback
            logback-classic
            1.2.11
            test
        
    



    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.1
                
                    17
                    17
                
            
        
    


mybatis-config.xml


        

    


    
        
        
            
            
            
            
        
    


    

CarMapper.xml




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,'102','霸图',50.30,'2024-11-05','新能源')
    

logback.xml




    
    
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
        
    
    
    
        
            
            ${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log
            
            30
        
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
        
        
        
            100MB
        
    

    
    
    
    
    

    
    
        
        
    

 

获取Sqlsession的工具类: 

package com.wsd;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @program: spring_learn
 * @description: Utility class for mybatis
 * @author: Mr.Wang
 * @create: 2023-06-17 17:38
 **/
public class SqlSessionUtil {

    private SqlSessionUtil(){}

    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 类加载时初始化sqlSessionFactory对象
     */
    static {
        try {
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 每调用一次openSession()可获取一个新的会话。
     *
     * @return 新的会话对象
     */
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }
}

test:

package com.wsd;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testInsert(){

        // 准备数据
        Map map = new HashMap<>();
        map.put("k1", "103");
        map.put("k2", "虚空");
        map.put("k3", 50.3);
        map.put("k4", "2021-01-07");
        map.put("k5", "新能源");

        SqlSession sqlSession = SqlSessionUtil.openSession();

        /*
        * 执行sql语句
        * parameter1 insertCar CarMapper.xml insert标签的id,
        * parameter2
        * */
        int count = sqlSession.insert("insertCar",);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();

    }
}

CarMapper.xml




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{k1},#{k2},#{k3},#{k4},#{k5})
    

mybatis将 sql 中 #{k1} 中的值k1作为 map 的 key ,从而获取k1对应的value 103,将 #{k1} 替换为 103,形成最终的sql 语句 

test result:

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=62981 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testInsert
2023-06-17 21:13:05.633 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-17 21:13:05.634 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 21:13:05.634 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 21:13:05.634 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 21:13:05.634 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 21:13:05.696 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-17 21:13:05.933 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 937744315.
2023-06-17 21:13:05.933 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-17 21:13:05.933 [main] DEBUG car.insertCar - ==>  Preparing: insert into t_car (id,car_num,brand,guide_price,produce_time,car_type) values (null,?,?,?,?,?)
2023-06-17 21:13:05.963 [main] DEBUG car.insertCar - ==> Parameters: 103(String), 虚空(String), 50.3(Double), 2021-01-07(String), 新能源(String)
2023-06-17 21:13:05.979 [main] DEBUG car.insertCar - <==    Updates: 1

1
2023-06-17 21:13:05.979 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-17 21:13:05.979 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-17 21:13:05.979 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-17 21:13:05.979 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 937744315 to pool.

Process finished with exit code 0
 

 

 mybatis02 CRUD_第1张图片

 

修改:

CarMapper.xml:




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    

test:

package com.wsd;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testInsert(){

        // 准备数据
        Map map = new HashMap<>();
        map.put("carNum", "104");
        map.put("brand", "301");
        map.put("guidePrice", 30.6);
        map.put("produceTime", "2021-03-06");
        map.put("carType", "新能源");

        SqlSession sqlSession = SqlSessionUtil.openSession();

        /*
        * 执行sql语句
        * parameter1 insertCar CarMapper.xml insert标签的id,
        * parameter2 map sql语句需要的数据
        * */
        int count = sqlSession.insert("insertCar",map);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();

    }
}

test result :

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=63121 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testInsert
2023-06-17 21:21:15.876 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-17 21:21:15.892 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 21:21:15.892 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 21:21:15.892 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 21:21:15.892 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 21:21:15.954 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-17 21:21:16.158 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 937744315.
2023-06-17 21:21:16.158 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-17 21:21:16.158 [main] DEBUG car.insertCar - ==>  Preparing: insert into t_car (id,car_num,brand,guide_price,produce_time,car_type) values (null,?,?,?,?,?)
2023-06-17 21:21:16.190 [main] DEBUG car.insertCar - ==> Parameters: 104(String), 301(String), 30.6(Double), 2021-03-06(String), 新能源(String)
2023-06-17 21:21:16.212 [main] DEBUG car.insertCar - <==    Updates: 1
1

2023-06-17 21:21:16.212 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-17 21:21:16.212 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-17 21:21:16.212 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-17 21:21:16.212 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 937744315 to pool.

Process finished with exit code 0
 

mybatis02 CRUD_第2张图片 

 

使用 pojo(简单普通的java对象)封装sql 需要的data

package com.wsd.pojo;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 21:53
 **/
public class Car {

    private Long id;
    private String carNum;
    private String brand;
    private Double guidePrice;
    private String produceTime;
    private String carType;

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

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

CarMapper.xml :




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    

 #{carNum} carNum 是 Car 的属性 carNum 

mybatis 根据  #{carNum} 中的 carNum 推断其getter 方法 为getCarNum(),

(推断: get + carNum首字母大写  )

然后调用 Car 的 getCarNum() 获取属性的值value,并以value 替代 #{carNum} 的位置

test:

package com.wsd;

import com.wsd.pojo.Car;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testInsertCarByPOJO(){
        // 创建POJO,封装数据
        Car car = new Car();
        car.setCarNum("104");
        car.setBrand("百花");
        car.setGuidePrice(36.23);
        car.setProduceTime("2020-02-22");
        car.setCarType("新能源");
        // 获取SqlSession对象
        SqlSession sqlSession = SqlSessionUtil.openSession();
        // 执行SQL,传数据
        int count = sqlSession.insert("insertCar", car);
        System.out.println("插入了几条记录" + count);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void testInsert(){

        // 准备数据
        Map map = new HashMap<>();
        map.put("carNum", "104");
        map.put("brand", "301");
        map.put("guidePrice", 30.6);
        map.put("produceTime", "2021-03-06");
        map.put("carType", "新能源");

        SqlSession sqlSession = SqlSessionUtil.openSession();

        /*
        * 执行sql语句
        * parameter1 insertCar CarMapper.xml insert标签的id,
        * parameter2 map sql语句需要的数据
        * */
        int count = sqlSession.insert("insertCar",map);
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();

    }
}
testInsertCarByPOJO result:

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=63996 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testInsertCarByPOJO
2023-06-17 22:07:27.838 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-17 22:07:27.846 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 22:07:27.846 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 22:07:27.846 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 22:07:27.846 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-17 22:07:27.908 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-17 22:07:28.112 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1870209957.
2023-06-17 22:07:28.112 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6f7923a5]
2023-06-17 22:07:28.112 [main] DEBUG car.insertCar - ==>  Preparing: insert into t_car (id,car_num,brand,guide_price,produce_time,car_type) values (null,?,?,?,?,?)
2023-06-17 22:07:28.144 [main] DEBUG car.insertCar - ==> Parameters: 104(String), 百花(String), 36.23(Double), 2020-02-22(String), 新能源(String)
2023-06-17 22:07:28.176 [main] DEBUG car.insertCar - <==    Updates: 1
插入了几条记录1

2023-06-17 22:07:28.176 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6f7923a5]
2023-06-17 22:07:28.176 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6f7923a5]
2023-06-17 22:07:28.176 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6f7923a5]
2023-06-17 22:07:28.176 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 1870209957 to pool.

Process finished with exit code 0
 

table:

mybatis02 CRUD_第3张图片 

 

delete

CarMapper.xml:




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    

    
        delete from t_car where car_num = #{carNum}
    

 test:

package com.wsd;

import com.wsd.pojo.Car;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testDeleteByCarNum(){
        // 获取SqlSession对象
        SqlSession sqlSession = SqlSessionUtil.openSession();
        // 执行SQL语句
        int count = sqlSession.delete("deleteByCarNum", "102");
        System.out.println("删除了几条记录:" + count);
        sqlSession.commit();
        sqlSession.close();
    }
    
}
只有一个占位符 #{},那么#{} 中的内容没有要求,随意
 delete from t_car where car_num = #{carNum} 
int count = sqlSession.delete("deleteByCarNum", "102");

test result:

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=50561 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testDeleteByCarNum
2023-06-18 09:20:35.649 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-18 09:20:35.664 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 09:20:35.664 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 09:20:35.664 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 09:20:35.664 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 09:20:35.789 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-18 09:20:36.166 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 937744315.
2023-06-18 09:20:36.166 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-18 09:20:36.182 [main] DEBUG car.deleteByCarNum - ==>  Preparing: delete from t_car where car_num = ?
2023-06-18 09:20:36.213 [main] DEBUG car.deleteByCarNum - ==> Parameters: 102(String)
2023-06-18 09:20:36.229 [main] DEBUG car.deleteByCarNum - <==    Updates: 7
删除了几条记录:7

2023-06-18 09:20:36.229 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-18 09:20:36.229 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-18 09:20:36.244 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@37e4d7bb]
2023-06-18 09:20:36.244 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 937744315 to pool.

Process finished with exit code 0
 

table data: 

 mybatis02 CRUD_第4张图片

 

update:

CarMapper.xml




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    

    
        delete from t_car where car_num = #{carNum}
    

    
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    

test:

package com.wsd;

import com.wsd.pojo.Car;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testUpdateCarById(){
        // 准备数据
        Car car = new Car();
        car.setId(172L);
        car.setCarNum("102");
        car.setBrand("微草");
        car.setGuidePrice(30.23);
        car.setProduceTime("2022-04-13");
        car.setCarType("新能源");
        // 获取SqlSession对象
        SqlSession sqlSession = SqlSessionUtil.openSession();
        // 执行SQL语句
        int count = sqlSession.update("updateCarById", car);
        System.out.println("更新了几条记录:" + count);
        sqlSession.commit();
        sqlSession.close();
    }
}

result:

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=52073 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testUpdateCarById
2023-06-18 10:13:59.845 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-18 10:13:59.865 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:13:59.865 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:13:59.865 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:13:59.865 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:13:59.946 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-18 10:14:00.277 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1870209957.
2023-06-18 10:14:00.277 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6f7923a5]
2023-06-18 10:14:00.277 [main] DEBUG car.updateCarById - ==>  Preparing: update t_car set car_num = ?, brand = ?, guide_price = ?, produce_time = ?, car_type = ? where id = ?
2023-06-18 10:14:00.325 [main] DEBUG car.updateCarById - ==> Parameters: 102(String), 微草(String), 30.23(Double), 2022-04-13(String), 新能源(String), 172(Long)
2023-06-18 10:14:00.348 [main] DEBUG car.updateCarById - <==    Updates: 1
更新了几条记录:1

2023-06-18 10:14:00.366 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6f7923a5]
2023-06-18 10:14:00.366 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6f7923a5]
2023-06-18 10:14:00.366 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6f7923a5]
2023-06-18 10:14:00.366 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 1870209957 to pool.

Process finished with exit code 0
 

table data : 

mybatis02 CRUD_第5张图片

selectOne :

 CarMapper.xml




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    

    
        delete from t_car where car_num = #{carNum}
    

    
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    

    

 

resultType="com.wsd.pojo.Car"  用com.wsd.pojo.Car 类型 来封装查询的结果

创建一个Car对象,将查询结果的字段赋值给对象相对应的属性

 

test :

package com.wsd;

import com.wsd.pojo.Car;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testSelectCarById(){
        // 获取SqlSession对象
        SqlSession sqlSession = SqlSessionUtil.openSession();
        // 执行SQL语句
        //selectOne 只会返回一条查询结果
        Object car = sqlSession.selectOne("selectCarById", 172);
        System.out.println(car);
        sqlSession.commit();
        sqlSession.close();
    }

}

result :

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=52438 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testSelectCarById
2023-06-18 10:34:15.185 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-18 10:34:15.192 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:34:15.192 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:34:15.200 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:34:15.200 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:34:15.250 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-18 10:34:15.430 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 157168588.
2023-06-18 10:34:15.430 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 10:34:15.440 [main] DEBUG car.selectCarById - ==>  Preparing: select * from t_car where id = ?
2023-06-18 10:34:15.476 [main] DEBUG car.selectCarById - ==> Parameters: 172(Integer)
2023-06-18 10:34:15.511 [main] DEBUG car.selectCarById - <==      Total: 1
Car{id=172, carNum='null', brand='微草', guidePrice=null, produceTime='null', carType='null'}

2023-06-18 10:34:15.530 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 10:34:15.530 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 10:34:15.530 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 157168588 to pool.

Process finished with exit code 0
 

 carNum='null'  是因为 Car 的属性carNum 与 列名 car_num 不一样,所以没能成功赋值

修改:

CarMapper.xml :




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    

    
        delete from t_car where car_num = #{carNum}
    

    
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    

    

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}

car_num as carNum 通过其别名来使查询结果的列名和Car 的属性可以相对应

 

 retest result :

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=52894 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testSelectCarById
2023-06-18 10:53:03.996 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-18 10:53:03.996 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:53:03.996 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:53:03.996 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:53:03.996 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 10:53:04.059 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-18 10:53:04.232 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 157168588.
2023-06-18 10:53:04.232 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 10:53:04.232 [main] DEBUG car.selectCarById - ==>  Preparing: select id,car_num as carNum,brand,guide_price as guidePrice,produce_time as produceTime,car_type as carType from t_car where id = ?
2023-06-18 10:53:04.264 [main] DEBUG car.selectCarById - ==> Parameters: 172(Integer)
2023-06-18 10:53:04.296 [main] DEBUG car.selectCarById - <==      Total: 1
Car{id=172, carNum='102', brand='微草', guidePrice=30.23, produceTime='2022-04-13', carType='新能源'}

2023-06-18 10:53:04.311 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 10:53:04.311 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 10:53:04.311 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 157168588 to pool.

Process finished with exit code 0
 

selectList        :

CarMapper.xml




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    

    
        delete from t_car where car_num = #{carNum}
    

    
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    

    

    
    

test:

package com.wsd;

import com.wsd.pojo.Car;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

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

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testSelectCarAll(){
        // 获取SqlSession对象
        SqlSession sqlSession = SqlSessionUtil.openSession();
        // 执行SQL语句
        List cars = sqlSession.selectList("selectCarAll");
        sqlSession.commit();
        sqlSession.close();
        // 输出结果
        cars.forEach(car -> System.out.println(car));
        
    }
}

result :

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=59232 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testSelectCarAll
2023-06-18 12:08:02.268 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-18 12:08:02.281 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:08:02.281 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:08:02.281 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:08:02.281 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:08:02.331 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-18 12:08:02.498 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 157168588.
2023-06-18 12:08:02.498 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 12:08:02.501 [main] DEBUG car.selectCarAll - ==>  Preparing: select id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType from t_car
2023-06-18 12:08:02.531 [main] DEBUG car.selectCarAll - ==> Parameters: 
2023-06-18 12:08:02.565 [main] DEBUG car.selectCarAll - <==      Total: 10
2023-06-18 12:08:02.567 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 12:08:02.568 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@95e33cc]
2023-06-18 12:08:02.568 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 157168588 to pool.
Car{id=165, carNum='6666', brand='丰田霸道', guidePrice=32.0, produceTime='2020-11-11', carType='燃油车'}
Car{id=166, carNum='1202', brand='大众速腾', guidePrice=30.0, produceTime='2020-11-11', carType='燃油车'}
Car{id=167, carNum='1203', brand='奔驰GLC', guidePrice=5.0, produceTime='2010-12-03', carType='燃油车'}
Car{id=168, carNum='1204', brand='奥迪Q7', guidePrice=3.0, produceTime='2009-10-11', carType='燃油车'}
Car{id=169, carNum='1205', brand='朗逸', guidePrice=4.0, produceTime='2001-10-11', carType='新能源'}
Car{id=171, carNum='1207', brand='奥迪A6', guidePrice=30.0, produceTime='2000-01-02', carType='燃油车'}
Car{id=172, carNum='102', brand='微草', guidePrice=30.23, produceTime='2022-04-13', carType='新能源'}
Car{id=181, carNum='103', brand='虚空', guidePrice=50.3, produceTime='2021-01-07', carType='新能源'}
Car{id=182, carNum='104', brand='301', guidePrice=30.6, produceTime='2021-03-06', carType='新能源'}
Car{id=183, carNum='104', brand='百花', guidePrice=36.23, produceTime='2020-02-22', carType='新能源'}

Process finished with exit code 0
 

    

mybatis02 CRUD_第6张图片 

 

namespace:

mybatis-config.xml :


        

    


    
        
        
            
            
            
            
        
    


    
    

有2个mapper文件

CarMapper.xml :




    
    
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
    

    
        delete from t_car where car_num = #{carNum}
    

    
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    

    

    
    

 CarMapper2.xml :




    
    

test :

package com.wsd;

import com.wsd.pojo.Car;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

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

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testNamespace(){
        // 获取SqlSession对象
        SqlSession sqlSession = SqlSessionUtil.openSession();
        // 执行SQL语句
        List cars = sqlSession.selectList("selectCarAll");
        sqlSession.commit();
        sqlSession.close();
        // 输出结果
        cars.forEach(car -> System.out.println(car));
    }

}

result :

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=59606 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testNamespace
2023-06-18 12:23:21.435 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-18 12:23:21.451 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:23:21.451 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:23:21.451 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:23:21.451 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.IllegalArgumentException: selectCarAll is ambiguous in Mapped Statements collection (try using the full name including the namespace, or rename one of the entries)
### Cause: java.lang.IllegalArgumentException: selectCarAll is ambiguous in Mapped Statements collection (try using the full name including the namespace, or rename one of the entries)

    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:153)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:145)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:135)
    at com.wsd.TestCarMapper.testNamespace(TestCarMapper.java:24)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: java.lang.IllegalArgumentException: selectCarAll is ambiguous in Mapped Statements collection (try using the full name including the namespace, or rename one of the entries)
    at org.apache.ibatis.session.Configuration$StrictMap.get(Configuration.java:1066)
    at org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:853)
    at org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:846)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
    ... 34 more


Process finished with exit code -1
 

selectCarAll is ambiguous in Mapped Statements collection (try using the full name including the namespace, or rename one of the entries)

selectCarAll在映射语句集合中是不明确的(尝试使用包含名称空间的全名,或者重命名其中一个条目

2个Mapper.xml 文件中都有 selectAll,不清楚具体使用哪一个

修改:

package com.wsd;

import com.wsd.pojo.Car;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

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

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-17 20:53
 **/
public class TestCarMapper {

    @Test
    public void testNamespace(){
        // 获取SqlSession对象
        SqlSession sqlSession = SqlSessionUtil.openSession();
        // 执行SQL语句
        List cars = sqlSession.selectList("car2.selectCarAll");
        sqlSession.commit();
        sqlSession.close();
        // 输出结果
        cars.forEach(car -> System.out.println(car));
    }

}

retest result :

"C:\Program Files\Java\jdk-17\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=59803 "-Didea.launcher.bin.path=C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\lib\idea_rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit-rt.jar;C:\Minecloud\IDEA_2019\IntelliJ IDEA 2019.1\plugins\junit\lib\junit5-rt.jar;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\test-classes;C:\Minecloud\IDEA_workspace\spring_learn\testMyBatis2\target\classes;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\mybatis\mybatis\3.5.10\mybatis-3.5.10.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\com\google\protobuf\protobuf-java\3.19.4\protobuf-java-3.19.4.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\junit\junit\4.13.2\junit-4.13.2.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;C:\Minecloud\maven_3.9\apache-maven-3.9.0\repo\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.TestCarMapper,testNamespace
2023-06-18 12:31:09.418 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2023-06-18 12:31:09.442 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:31:09.442 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:31:09.442 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:31:09.442 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
2023-06-18 12:31:09.512 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
2023-06-18 12:31:09.764 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1939022383.
2023-06-18 12:31:09.764 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7393222f]
2023-06-18 12:31:09.779 [main] DEBUG car2.selectCarAll - ==>  Preparing: select brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType from t_car
2023-06-18 12:31:09.842 [main] DEBUG car2.selectCarAll - ==> Parameters: 
2023-06-18 12:31:09.943 [main] DEBUG car2.selectCarAll - <==      Total: 10
2023-06-18 12:31:09.943 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7393222f]
2023-06-18 12:31:09.943 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7393222f]
2023-06-18 12:31:09.943 [main] DEBUG o.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 1939022383 to pool.
Car{id=null, carNum='null', brand='丰田霸道', guidePrice=32.0, produceTime='2020-11-11', carType='燃油车'}
Car{id=null, carNum='null', brand='大众速腾', guidePrice=30.0, produceTime='2020-11-11', carType='燃油车'}
Car{id=null, carNum='null', brand='奔驰GLC', guidePrice=5.0, produceTime='2010-12-03', carType='燃油车'}
Car{id=null, carNum='null', brand='奥迪Q7', guidePrice=3.0, produceTime='2009-10-11', carType='燃油车'}
Car{id=null, carNum='null', brand='朗逸', guidePrice=4.0, produceTime='2001-10-11', carType='新能源'}
Car{id=null, carNum='null', brand='奥迪A6', guidePrice=30.0, produceTime='2000-01-02', carType='燃油车'}
Car{id=null, carNum='null', brand='微草', guidePrice=30.23, produceTime='2022-04-13', carType='新能源'}
Car{id=null, carNum='null', brand='虚空', guidePrice=50.3, produceTime='2021-01-07', carType='新能源'}
Car{id=null, carNum='null', brand='301', guidePrice=30.6, produceTime='2021-03-06', carType='新能源'}
Car{id=null, carNum='null', brand='百花', guidePrice=36.23, produceTime='2020-02-22', carType='新能源'}

Process finished with exit code 0
 

2个不同 namespace 中 可以使用相同的 id,加上 namespace 作为前缀就可以将 2个相同的 id 区分出来

你可能感兴趣的:(java,mybatis,开发语言)