MyBatis快速上手

单独使用MyBatis

整体结构

源码:https://git.nowcoder.com/698510949/learning-mybatis

main
    java
        dao
            StudentDao.java
        domain
            Student.java
    resources
        mapper
            student-mapper.xml
        mybatis-config.xml
test
    java
        MyTest

简要步骤

  1. 配置环境(mybatis依赖,mysql数据库,mysql依赖等)
  2. 配置mybatis的总配置文件
  3. 配置各个mapper的配置文件
  4. 写Dao类、实体类(或者还有Service类等)
  5. 测试
    • 使用SqlSessionFactoryBuilder加载mybatis配置文件,创建一个SqlSessionFactory(通常为单例)
    • 使用SqlSessionFactory创建一个SqlSession
    • 用这个session直接执行insert、select等操作,或者先调用getMapper方法获取对应的Mapper类,然后用这个Mapper来执行各项操作
    • 执行完后调用commit提交,关闭session

导入依赖

直接导入org.mybatis的依赖,而不是org.mybatis.spring.boot的依赖。

其他还需要导入的包有mysql和junit。mysql提供了jdbc来连接数据库。

<?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.rua.testbench</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.5.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

从XML中创建SqlSessionFactory

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

这里的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>
    <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/learn_mybatis?serverTimezone=GMT"/>
                <property name="username" value="admin"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/student-mapper.xml"/>
    </mappers>
</configuration>

mappers标签里面的mapper可以指定resource,表示具体的xml文件,也可以是:

  • url,表示包含各个mapper的xml文件的目录
  • class,定义在Dao里的Mapper接口
  • name,包含Mapper接口的包名

从SqlSessionFactory中获取SqlSession

try(SqlSession session = sqlSessionFactory.openSession()){
    Student bob = new Student(1,"Bob");
    session.insert("dao.StudentDao.insertStudent",bob); //前一个属性是Mapper类的某一方法
    Student returnedBob = session.selectOne("dao.StudentDao.selectStudent",1);
    session.commit();
}

写一个Mapper的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="dao.StudentDao">
    <insert id="insertStudent" >
        INSERT INTO student(id,name) VALUES(#{id},#{name});
    </insert>
    <select id="selectStudent" resultType="domain.Student">
        SELECT id,name FROM student WHERE id=#{id};
    </select>
</mapper>

这里面namespace必须与对应的Mapper类名,而insert里面的id也必须与对应的方法相同。

这里所有的类名都是用的完全限定名,比如dao.StudentDao,domain.Student。

Student类

package domain;

import java.util.Objects;

public class Student {
    private int id;
    private String name;
    //构造函数
    //getter和setter
    //equals和hashcode
}

StudentDao类

package dao;

import domain.Student;

public interface StudentDao {
    public boolean insertStudent(int id,String name);
    public Student selectStudent(int id);
}

这个类是和MyBatis实现映射的核心类。为了保证映射关系,需要非常注意类名、方法名和参数。

测试类MyTest

import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;

public class MyTest {
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try(SqlSession session = sqlSessionFactory.openSession()){
            Student bob = new Student(1,"Bob");
            session.insert("dao.StudentDao.insertStudent",bob);
            Student returnedBob = session.selectOne("dao.StudentDao.selectStudent",1);
            Assertions.assertTrue(bob.equals(returnedBob));
            session.commit();
        }
    }
}
全部评论

相关推荐

牛客569470950号:也不知道是哪个群体45年前鬼哭狼嚎的为自己争取的被剥削的权利
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务