使用Mybatis实现基本的增删改查------数据输入

创建一个空的Maven项目,删去src,用作存储pom的父项目

pom中存放下列依赖:

java 复制代码
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.11</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
    </dependencies>

创建Module在pom中加入测试依赖

java 复制代码
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

创建数据库

java 复制代码
CREATE TABLE student(
stuID INTEGER NOT NULL,
stuName VARCHAR(20),
stuSalary DECIMAL(10,3) 
)

创建实体类

java 复制代码
package su.Entity;

/**
 * @author haustsusu
 * @create 2023-09-08-19:12
 */
public class Student {
    private Integer stuId;
    private String stuName;
    private Double stuSalary;

    public Student() {
    }

    public Student(Integer stuId, String stuName, Double stuSalary) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuSalary = stuSalary;
    }

    public Integer getStuId() {
        return stuId;
    }

    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public Double getStuSalary() {
        return stuSalary;
    }

    public void setStuSalary(Double stuSalary) {
        this.stuSalary = stuSalary;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuSalary=" + stuSalary +
                '}';
    }
}

创建Mybatis框架需要创建Mapper.xml,Mapper接口,MybatisConfig配置文件

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>
    <!--    引入jdbc.properties-->
    <properties resource="jdbc.properties"></properties>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>



    <environments default="development">
<!--        表示配置Mybatis的一个具体环境-->
        <environment id="development">
<!--            mybatis内置的事务管理器-->
            <transactionManager type="JDBC"/>
<!--            配置数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--     而 mappers 标签就是用来配置需要加载的 sql 映射配置文件路径的-->
    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

Mapper接口

java 复制代码
public interface stuMapper {
    List<Student> QueryStudents();

    Student QueryStudent(Integer Id);

}

Mybatis配置文件

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>
    <!--    引入jdbc.properties-->
    <properties resource="jdbc.properties"></properties>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>



    <environments default="development">
<!--        表示配置Mybatis的一个具体环境-->
        <environment id="development">
<!--            mybatis内置的事务管理器-->
            <transactionManager type="JDBC"/>
<!--            配置数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--     而 mappers 标签就是用来配置需要加载的 sql 映射配置文件路径的-->
    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

最后在测试类中运行

java 复制代码
public class StudentTest {
    @Test
    public void test01() throws IOException {
        //1.读取外部配置文件,获取一个输入流
        InputStream resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");

        //2.创建sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        //3.获取Sqlsession对象[自动开启JDBC]
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4.获取代理mapper对象
        stuMapper mapper = sqlSession.getMapper(stuMapper.class);

        //执行查询所有学生的方法
        List<Student> students = (List<Student>) mapper.QueryStudents();
        //查询id学生的方法
        Student student = mapper.QueryStudent(10001);
        System.out.println("某个学生--------------------");
        System.out.println(student);
        System.out.println("某个学生--------------------");

        for (Student s:students){
            System.out.println(s);
        }
        //5.管理资源与提交事务
        sqlSession.close();

    }
}

结果:

java 复制代码
E:\Java\jdk1.8.0_301\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:E:\IDEA\idea\IntelliJ IDEA 2020.1\lib\idea_rt.jar=8837:E:\IDEA\idea\IntelliJ IDEA 2020.1\bin" -Dfile.encoding=UTF-8 -classpath "E:\IDEA\idea\IntelliJ IDEA 2020.1\lib\idea_rt.jar;E:\IDEA\idea\IntelliJ IDEA 2020.1\plugins\junit\lib\junit5-rt.jar;E:\IDEA\idea\IntelliJ IDEA 2020.1\plugins\junit\lib\junit-rt.jar;E:\java\jdk1.8.0_301\jre\lib\charsets.jar;E:\java\jdk1.8.0_301\jre\lib\deploy.jar;E:\java\jdk1.8.0_301\jre\lib\ext\access-bridge-64.jar;E:\java\jdk1.8.0_301\jre\lib\ext\cldrdata.jar;E:\java\jdk1.8.0_301\jre\lib\ext\dnsns.jar;E:\java\jdk1.8.0_301\jre\lib\ext\jaccess.jar;E:\java\jdk1.8.0_301\jre\lib\ext\jfxrt.jar;E:\java\jdk1.8.0_301\jre\lib\ext\localedata.jar;E:\java\jdk1.8.0_301\jre\lib\ext\nashorn.jar;E:\java\jdk1.8.0_301\jre\lib\ext\sunec.jar;E:\java\jdk1.8.0_301\jre\lib\ext\sunjce_provider.jar;E:\java\jdk1.8.0_301\jre\lib\ext\sunmscapi.jar;E:\java\jdk1.8.0_301\jre\lib\ext\sunpkcs11.jar;E:\java\jdk1.8.0_301\jre\lib\ext\zipfs.jar;E:\java\jdk1.8.0_301\jre\lib\javaws.jar;E:\java\jdk1.8.0_301\jre\lib\jce.jar;E:\java\jdk1.8.0_301\jre\lib\jfr.jar;E:\java\jdk1.8.0_301\jre\lib\jfxswt.jar;E:\java\jdk1.8.0_301\jre\lib\jsse.jar;E:\java\jdk1.8.0_301\jre\lib\management-agent.jar;E:\java\jdk1.8.0_301\jre\lib\plugin.jar;E:\java\jdk1.8.0_301\jre\lib\resources.jar;E:\java\jdk1.8.0_301\jre\lib\rt.jar;D:\SSM_MybatisOne\SSM_Mybatis_Student\target\test-classes;D:\SSM_MybatisOne\SSM_Mybatis_Student\target\classes;C:\Users\小苏\.m2\repository\junit\junit\4.13.2\junit-4.13.2.jar;C:\Users\小苏\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\小苏\.m2\repository\org\mybatis\mybatis\3.5.11\mybatis-3.5.11.jar;C:\Users\小苏\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 StudentCRUDTest.StudentTest,test01
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1909546776.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@71d15f18]
==>  Preparing: select stuID stuId,stuName stuName,stuSalary stuSalary from student
==> Parameters: 
<==    Columns: stuId, stuName, stuSalary
<==        Row: 10001, 苏宝全, 2000.365
<==        Row: 10002, 苏风严, 3000.451
<==      Total: 2
==>  Preparing: select stuID stuId,stuName stuName,stuSalary stuSalary from student where stuId=?
==> Parameters: 10001(Integer)
<==    Columns: stuId, stuName, stuSalary
<==        Row: 10001, 苏宝全, 2000.365
<==      Total: 1
某个学生--------------------
Student{stuId=10001, stuName='苏宝全', stuSalary=2000.365}
某个学生--------------------
Student{stuId=10001, stuName='苏宝全', stuSalary=2000.365}
Student{stuId=10002, stuName='苏风严', stuSalary=3000.451}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@71d15f18]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@71d15f18]
Returned connection 1909546776 to pool.

Process finished with exit code 0

场景一:传入单个数据:(数据名可以随意写,但不建议)

场景二:传入一个实体对象

场景三:传入多个简单类型

mapper接口中的方法不能出现重载,重载会导致在Mapper.xml中无法根据id查找到对应的接口方法

场景四:传入Map

相关推荐
鹿屿二向箔13 小时前
基于SSM(Spring + Spring MVC + MyBatis)框架的汽车租赁共享平台系统
spring·mvc·mybatis
沐雪架构师16 小时前
mybatis连接PGSQL中对于json和jsonb的处理
json·mybatis
鹿屿二向箔18 小时前
基于SSM(Spring + Spring MVC + MyBatis)框架的咖啡馆管理系统
spring·mvc·mybatis
aloha_7891 天前
从零记录搭建一个干净的mybatis环境
java·笔记·spring·spring cloud·maven·mybatis·springboot
毕业设计制作和分享1 天前
ssm《数据库系统原理》课程平台的设计与实现+vue
前端·数据库·vue.js·oracle·mybatis
paopaokaka_luck1 天前
基于Spring Boot+Vue的助农销售平台(协同过滤算法、限流算法、支付宝沙盒支付、实时聊天、图形化分析)
java·spring boot·小程序·毕业设计·mybatis·1024程序员节
cooldream20091 天前
Spring Boot中集成MyBatis操作数据库详细教程
java·数据库·spring boot·mybatis
不像程序员的程序媛1 天前
mybatisgenerator生成mapper时报错
maven·mybatis
小布布的不1 天前
MyBatis 返回 Map 或 List<Map>时,时间类型数据,默认为LocalDateTime,响应给前端默认含有‘T‘字符
前端·mybatis·springboot
背水2 天前
Mybatis基于注解的关系查询
mybatis