mybatis02 CRUD

news2024/9/23 7:23:58

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

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

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wsd</groupId>
    <artifactId>testMyBatis2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <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>8.0.30</version>
        </dependency>

        <!-- junit依赖 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        
        <!--logbak 日志框架 依赖-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>



    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE configuration
                PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
                "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--未指定时自动查找-->
<!--<settings>
    <setting name="logImpl" value="SLF4J" />
</settings>-->
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </dataSource>
    </environment>
</environments>
<mappers>
    <mapper resource="CarMapper.xml"/>
</mappers>
</configuration>

CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="car">
    <!--insert sql:保存一个汽车信息-->
    <insert id="insertCar">
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,'102','霸图',50.30,'2024-11-05','新能源')
    </insert>
</mapper>

logback.xml

<?xml version="1.0" encoding="UTF-8"?>

<configuration debug="false">
    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 按照每天生成日志文件 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>100MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <!--mybatis log configure-->
    <logger name="com.apache.ibatis" level="TRACE"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>

    <!-- 日志输出级别,logback日志级别包括五个:TRACE < DEBUG < INFO < WARN < ERROR -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>

</configuration>

 

获取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<String, Object> 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

<?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="car">
    <!--insert sql:保存一个汽车信息-->
    <insert id="insertCar">
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type)
        values
            (null,#{k1},#{k2},#{k3},#{k4},#{k5})
    </insert>
</mapper>

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
 

 

 

 

修改:

CarMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="car">
    <!--insert sql:保存一个汽车信息-->
    <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>

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<String, Object> 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
 

 

 

使用 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 :

<?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="car">
    <!--insert sql:保存一个汽车信息-->
    <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>

 #{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<String, Object> 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:

 

 

delete

CarMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="car">
    <!--insert sql:保存一个汽车信息-->
    <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>

    <delete id="deleteByCarNum">
        delete from t_car where car_num = #{carNum}
    </delete>
</mapper>

 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 id="deleteByCarNum"> delete from t_car where car_num = #{carNum} </delete>
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: 

 

 

update:

CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="car">
    <!--insert sql:保存一个汽车信息-->
    <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>

    <delete id="deleteByCarNum">
        delete from t_car where car_num = #{carNum}
    </delete>

    <update id="updateCarById">
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    </update>
</mapper>

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 : 

selectOne :

 CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="car">
    <!--insert sql:保存一个汽车信息-->
    <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>

    <delete id="deleteByCarNum">
        delete from t_car where car_num = #{carNum}
    </delete>

    <update id="updateCarById">
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    </update>

    <select id="selectCarById" resultType="com.wsd.pojo.Car">
        select * from t_car where id = #{id}
    </select>
</mapper>

 

<select id="selectCarById" resultType="com.wsd.pojo.Car">
    select * from t_car where id = #{id}
</select>

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 :

<?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="car">
    <!--insert sql:保存一个汽车信息-->
    <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>

    <delete id="deleteByCarNum">
        delete from t_car where car_num = #{carNum}
    </delete>

    <update id="updateCarById">
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    </update>

    <select id="selectCarById" resultType="com.wsd.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>

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

<?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="car">
    <!--insert sql:保存一个汽车信息-->
    <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>

    <delete id="deleteByCarNum">
        delete from t_car where car_num = #{carNum}
    </delete>

    <update id="updateCarById">
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    </update>

    <select id="selectCarById" resultType="com.wsd.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>

    <!--虽然结果是List集合,但是resultType属性需要指定的是List集合中元素的类型。-->
    <select id="selectCarAll" resultType="com.wsd.pojo.Car">
        <!--记得使用as起别名,让查询结果的字段名和java类的属性名对应上。-->
        select
        id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType
        from
        t_car
    </select>
</mapper>

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

    

 

 

namespace:

mybatis-config.xml :

<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE configuration
                PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
                "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--未指定时自动查找-->
<!--<settings>
    <setting name="logImpl" value="SLF4J" />
</settings>-->
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </dataSource>
    </environment>
</environments>
<mappers>
    <mapper resource="CarMapper.xml"/>
    <mapper resource="CarMapper2.xml" />
</mappers>
</configuration>

有2个mapper文件

CarMapper.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="car">
    <!--insert sql:保存一个汽车信息-->
    <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>

    <delete id="deleteByCarNum">
        delete from t_car where car_num = #{carNum}
    </delete>

    <update id="updateCarById">
        update t_car set
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    </update>

    <select id="selectCarById" resultType="com.wsd.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>

    <!--虽然结果是List集合,但是resultType属性需要指定的是List集合中元素的类型。-->
    <select id="selectCarAll" resultType="com.wsd.pojo.Car">
        <!--记得使用as起别名,让查询结果的字段名和java类的属性名对应上。-->
        select
        id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType
        from
        t_car
    </select>
</mapper>

 CarMapper2.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="car2">
    <!--虽然结果是List集合,但是resultType属性需要指定的是List集合中元素的类型。-->
    <select id="selectCarAll" resultType="com.wsd.pojo.Car">
        <!--记得使用as起别名,让查询结果的字段名和java类的属性名对应上。-->
        select
         brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType
        from
        t_car
    </select>
</mapper>

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<Object> 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<Object> 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 区分出来

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/658912.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Java入门】-- Java基础详解之 [Java面向对象编程(初级)]

目录 1.类与对象 2.类与对象的区别与联系 3.对象在JVM内存中的存在形式(重要) 4.属性/成员变量/字段 5.如何创建对象 6.类和对象的内存分配机制 7.面向对象的三大特征&#xff1f; 8.面向对象和面向过程&#xff1f; 9.匿名对象 10.方法(method) 11.方法的重载(over…

一个AI关键词能卖500块?AI绘画引发研究关键词的商机

一个AI关键词能卖500块&#xff1f;AI绘画引发研究关键词的商机&#xff01; 绘画一直被人们看作是视觉艺术的呈现方式。通常情况下&#xff0c;学习绘画需要理解调色、构图和线条等要素。然而&#xff0c;自从AI介入绘画领域后&#xff0c;绘画的"画风"迅速发生了变…

Mac下载安装vscode

1. 下载 先从 https://code.visualstudio.com 下载Mac版vscode。 2. 安装 下载之后在浏览器的下载中点击安装vscode 下载的时候会有提示 有时候还需要配置【安全性与隐私】&#xff0c;即允许App Store和被认可的开发者安装软件 3. 简单配置 默认进来会要求选择主题&a…

1初步整合ABP模块化

1 首先创建一个WebApi项目 2 初步整合ABP模块化 Abp官网&#xff0c;这里我们先初步整合WebApi模块化&#xff0c;待程序运行起来&#xff0c;后续文章我们再对Abp进行深入。 2.1 NuGet&#xff1a;包Volo.Abp Volo,Abp&#xff1a;模块化必备 2.2 NuGet&#xff1a;Volo.Abp.A…

scratch lenet(5): 快速生成随机数的C语言实现

文章目录 1. 目的2. 使用 rand() 的正确姿势3. 使用 TAOCP 公式3.1 实现3.2 使用 4. 随机数&#xff1a;用于 Xavier Glorot 初始化4.1 Xavier Glorot 初始化是什么4.2 使用C语言执行 Xavier Glorot 初始化 5. References 1. 目的 用于 lenet 网络训练开始时&#xff0c; weig…

神奇的 SQL 之 HAVING 一个容易被忽视的主角!

初识 HAVING 关于 SQL 中的 HAVING&#xff0c;相信大家都不陌生&#xff0c;它往往与 GROUP BY 配合使用&#xff0c;为聚合操作指定条件 说到指定条件&#xff0c;我们最先想到的往往是 WHERE 子句&#xff0c;但 WHERE 子句只能指定行的条件&#xff0c;而不能指定组的条件…

使用css3如何实现一个文字打印效果

前言 在很多网站首页介绍页里,为了吸引用户,暂留更长时间,使用了一些css3动画的 示例效果 文字打印.gif 实现这个动画原理 想要实现这个动画,改变元素的宽度,结合动画css3关键帧实现 具体代码如下所示 <!DOCTYPE html> <html lang"en"><head><m…

[元带你学: eMMC协议详解 14] 数据擦除(Erase) 详解

依JEDEC eMMC 5.1及经验辛苦整理&#xff0c;付费内容&#xff0c;禁止转载。 所在专栏 《元带你学: eMMC协议详解》 内容摘要 全文 4200字&#xff0c; 主要内容介绍了各种擦除操作概念以记用法&#xff0c;总结了不同擦除操作的区别&#xff0c; 根据不同安全级别和应用场景…

管理类联考——英语二——技巧篇——写作——A节——书信——九类书信黄金句型(背诵版)

九类书信黄金句型(背诵版) 1&#xff0e;询问信 询问信开头常用句式 l would be grateful if you could send me information about. . . l am writing to see if it is possible for you to provide me with information about. . . l am writing to ask you if/ whether. .…

15-5.自定义组件的通信

目录 1 构建组件间的父子关系 2 父向子传值-属性绑定 3 子向父传值-自定义事件 4 获取组件实例 1 构建组件间的父子关系 需要在father1.json中引入son1&#xff0c;然后再father.wxml中使用son1 2 父向子传值-属性绑定 属性绑定很像props。属性绑定只能传递普通类型…

3C - SiC、4H-SiC和6H -SiC

3C-SiC是立方结构 4H-SiC是四方结构 6H-SiC是双六方结构 它们的区别主要在于原子排列模式和配位数。3C-SiC具有最高的理论电子速度,但也有最大的杂质腐蚀痕迹。4H-SiC和6H-SiC具有更好的成本效益与设备可靠性。 3C-SiC具有立方晶系结构&#xff0c;每个硅原子被四个碳原子和四…

深度学习(22)——YOLO系列(3)

深度学习&#xff08;22&#xff09;——YOLO系列&#xff08;3&#xff09; 文章目录 深度学习&#xff08;22&#xff09;——YOLO系列&#xff08;3&#xff09;1. BOF(bag of freebies)2. Mosaic data augmentation3. 数据增强4. self-adversarial-training&#xff08;SAT…

LwIP系列(2):动态内存池管理(memp.c)详细分析

前言 我们在学习Lwip源码时&#xff0c;内存管理是绕不开的一个重点&#xff0c;我们在看相关的代码时&#xff0c;经常会看到memp_malloc 和 mem_malloc, 其中&#xff1a; &#xff08;1&#xff09;memp_malloc是从内存池中申请内存&#xff0c;具体实现在memp.c memp.h。…

木马攻击与防护

目录 一、初识Trojan木马 1.1 木马概念 1.2 木马特点 1.2.1 欺骗性 1.2.2 隐蔽性 1.2.3 非授权性 1.3 病毒和木马 1.3.1 病毒的特点 1.3.2 病毒的主要目的 1.3.3 病毒例子 1.3.4 木马程序企图 1.3.5 木马危害 1.3.6 病毒与木马的区别 1.4 木马种类 1.4.1 远程访…

机器学习之KNN算法:基于pytorch在MNIST数据集上实现数据分类预测

1 KNN算法介绍 KNN算法又叫做K近邻算法&#xff0c;是众多机器学习算法里面最基础入门的算法。KNN算法是最简单的分类算法之一&#xff0c;同时&#xff0c;它也是最常用的分类算法之一。KNN算法是有监督学习中的分类算法&#xff0c;它看起来和Kmeans相似&#xff08;Kmeans是…

CMake中的find_package(xxx REQUIRED)在windows平台怎么解

最近在编译FastDDS时&#xff0c;遇到了这个问题&#xff0c;使用CMake构建时提示找不到库。 下载的源代码不能一次性编过是最让人头疼的问题&#xff0c;这种开源代码通常都是迭代了很多版本&#xff0c;各种配置信息如果不在文档中说明&#xff0c;全靠自己去摸索确实会让人头…

idea运行java项目提示异常: java.security.InvalidKeyException: Illegal key size

idea运行java项目提示异常&#xff1a;java.lang.IllegalArgumentException: java.security.InvalidKeyException: Illegal key size 参考&#xff1a;java.security.InvalidKeyException: Illegal key size_gqltt的博客-CSDN博客 产生错误原因&#xff1a;为了数据代码在传输过…

4、做什么类型的产品经理

1、如何选择适合自己的产品经理岗位 怎么选择适合自己的这个产品经理岗位呢&#xff1f;建议大家是先考虑行业&#xff0c;再考虑其他的。 考虑行业就是说我要做什么行业的产品经理,然后再考虑在这个行业里面具体的你要做前端还是后端或者是APP端&#xff0c;还是web端&#x…

【MySQL】不就是MySQL——索引

前言 嗨&#xff01;小伙伴们周末快乐呀&#xff01;想必你们周末都在家里边呆着吧&#xff0c;外面实在是太热了&#xff01;在家里吹着空调做着自己喜欢做的事情吧&#xff01;本期我们主要学习的是MySQL中的约束条件。 目录 前言 索引概述 外键约束 1.概念 2.语法 1.添加…

【HTML界面设计(二)】说说模块、登录界面

记录很早之前写的前端界面&#xff08;具体时间有点久远&#xff09; 一、说说模板 采用 适配器&#xff08;Adapter&#xff09;原理 来设计这款说说模板&#xff0c;首先看一下完整效果 这是demo样图&#xff0c;需要通过业务需求进行修改的部分 这一部分&#xff0c;就是dem…