MyBatis教程

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。


一、环境变量

  • jdk 8 +
  • MySQL 8.0.33
  • maven-3.6.1
  • IDEA 2020.1 最新版本也没有问题

二、使用步骤

1.创建Maven

 

2.搭建数据库

这里使用的是MySQL数据库,sql语句如下

create database if not exists pratice;
use pratice;
-- 学生表
-- Student(s_id,s_name,s_birth,s_sex) :学生编号、姓名、年月、性别
CREATE TABLE
IF NOT EXISTS `Student` (
	`s_id` VARCHAR (20),
	`s_name` VARCHAR (20) NOT NULL DEFAULT '',
	`s_birth` VARCHAR (20) NOT NULL DEFAULT '',
	`s_sex` VARCHAR (10) NOT NULL DEFAULT '',
	PRIMARY KEY (`s_id`)
) ENGINE = INNODB DEFAULT CHARSET = utf8;
-- 插入数据
INSERT INTO Student VALUES ('01', '赵雷', '1990-01-01', '男');
INSERT INTO Student VALUES ('02', '钱电', '1990-12-21', '男');
INSERT INTO Student VALUES ('03', '孙风', '1990-05-20', '男');
INSERT INTO Student VALUES ('04', '李云', '1990-08-06', '男');
INSERT INTO Student VALUES ('05', '周梅', '1991-12-01', '女');
INSERT INTO Student VALUES ('06', '吴兰', '1992-03-01', '女');
INSERT INTO Student VALUES ('07', '郑竹', '1989-07-01', '女');
INSERT INTO Student VALUES ('08', '王菊', '1990-01-20', '女');

创建了一个pratice数据库以及Student表

3.导入相关包

找到Maven项目里的pom.xml,导入Mybatis相关包。

<?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>nj.zb.kb22</groupId>
    <artifactId>jdbckb222</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>jdbckb222 Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.2</version>
        </dependency>

    </dependencies>


    <build>
        <finalName>jdbckb222</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

4.配置resources文件

找到项目里的resources文件,没有就自己建一个

自己建的要把该文件夹标记为Resources root。

先在resources文件夹下创建database.properties文件,注意的是url,user以及password都要根据自己的实际情况更改。

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.153.149:3306/pratice?useSSL=false&serverTimezone=UTC
user=root
password=123456

然后在resources文件夹下创建mybatis-config.xml文件,配置自己的数据库地址、名字、密码以及mysql驱动。package name是根据之后创建的实体所在目录进行更改的

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <properties resource="database.properties"></properties>
   <typeAliases>
       <package name="nj.zb.kb22.pojo"/>
   </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

整理项目目录

5.创建实体类

在pojo文件夹下,新建一个class文件,Student.class

package nj.zb.kb22.pojo;

import java.util.List;

public class Student {
    private String s_id;
    private String s_name;
    private String s_birth;
    private String s_sex;


    @Override
    public String toString() {
        return "Student{" +
                "s_id='" + s_id + '\'' +
                ", s_name='" + s_name + '\'' +
                ", s_birth='" + s_birth + '\'' +
                ", s_sex='" + s_sex + '\'' +
                '}';
    }

    public Student() {
    }

    public Student(String s_id, String s_name, String s_birth, String s_sex) {
        this.s_id = s_id;
        this.s_name = s_name;
        this.s_birth = s_birth;
        this.s_sex = s_sex;
    }

    public String getS_id() {
        return s_id;
    }

    public void setS_id(String s_id) {
        this.s_id = s_id;
    }

    public String getS_name() {
        return s_name;
    }

    public void setS_name(String s_name) {
        this.s_name = s_name;
    }

    public String getS_birth() {
        return s_birth;
    }

    public void setS_birth(String s_birth) {
        this.s_birth = s_birth;
    }

    public String getS_sex() {
        return s_sex;
    }

    public void setS_sex(String s_sex) {
        this.s_sex = s_sex;
    }
}

6.编写接口类

在dao文件夹下创建IStudentDao.interface,里面编写增删改查四个方法

package nj.zb.kb22.dao;

import nj.zb.kb22.pojo.Student;

import java.util.List;

public interface IStudentDao {
    List<Student> getAllStudent();
    public Integer save(Student student);
    public Integer update(Student student);
    public Integer delete(Student student);
}

7.编写xml配置文件

创建StudentDao.xml文件,可以将其创建在resources文件夹下

<?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="nj.zb.kb22.dao.IStudentDao">
    <select id="getAllStudent" resultType="Student">
        select s_id,s_name,s_birth,s_sex from student
    </select>
    <insert id="save">
        insert into student(s_id,s_name,s_birth,s_sex)
        values(#{s_id},#{s_name},#{s_birth},#{s_sex})
    </insert>
    <update id="update">
        update student set s_name=#{s_name},s_birth=#{s_birth},s_sex=#{s_sex} where s_id=#{s_id}
    </update>
    <delete id="delete">
        delete from student where s_id=#{s_id}
    </delete>

    <resultMap id="studentMap" type="Student">
        <id column="s_id" property="s_id"></id>
        <result column="s_name" property="s_name"></result>
        <result column="s_birth" property="s_birth"></result>
        <result column="s_sex" property="s_sex"></result>
        <collection property="teachers" ofType="Teacher">
            <id column="t_id" property="t_id"></id>
            <result column="t_name" property="t_name"></result>
        </collection>
 
</mapper>

将刚才记得要将刚才的Student.xml注册到mybatis-config.xml文件中,非常重要,此后每编写一个Mapper.xm文件都要注册一次!!!,在mybatis-config.xml文件更新为如下代码

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <properties resource="database.properties"></properties>
   <typeAliases>
       <package name="nj.zb.kb22.pojo"/>
   </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="nj/zb/mysql/StudentDao.xml"/>
    </mappers>
</configuration>

8.编写测试类

在test文件夹下创建测试类,可命名为StudentTest

测试增删改查功能,直接右击@Test下的方法,点击运行,查看测试结果。

package nj.zb.kb22;

import nj.zb.kb22.dao.IStudentDao;
import nj.zb.kb22.pojo.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class StudentTest {
    //工厂模式
    SqlSessionFactory sqlSessionFactory=null;
    //会话Session
    SqlSession sqlSession=null;
    //Dao对象
    IStudentDao studentDao=null;

    @Before
    public void setUp(){
        System.out.println("hello before");
        InputStream inputStream = StudentTest.class.getClassLoader()
                .getResourceAsStream("mybatis-config.xml");
        //创建SessionFactory的创建者builder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //获取构建工厂
        sqlSessionFactory=builder.build(inputStream);
        //打开会话
        sqlSession=sqlSessionFactory.openSession();
        //获取sql执行者
        studentDao=sqlSession.getMapper(IStudentDao.class);
    }

    @Test
    public void testA(){
        System.out.println("hello test java");
        System.out.println(sqlSession);
        System.out.println(studentDao);
        List<Student> allStudent=studentDao.getAllStudent();
        for (Student student :
                allStudent) {
            System.out.println(student);
        }
    }

    @Test
    public void testStudentSave(){
        Student student = new Student();
        student.setS_id("09");
        student.setS_name("坤坤");
        student.setS_birth("1996-09-23");
        student.setS_sex("男");
        int save = studentDao.save(student);
        System.out.println(save);

    }
    @Test
    public void testStudentUpdate(){
        Student student = new Student();
        student.setS_id("09");
        student.setS_name("坤坤");
        student.setS_birth("1996-10-23");
        student.setS_sex("男");
        int update = studentDao.update(student);
        System.out.println(update);

    }
    @After
    public void tearDown(){
        System.out.println("hello after");
        sqlSession.commit();
        sqlSession.close();
        System.out.println("game over");
    }
}

以下为测试成功的结果图:


总结

MyBatis还有很多的功能,文章这里讲的是配置以及最基础的用法,更高级的用法作者还需要继续学习。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值