创建项目

导入依赖

    <!--导入mybatis、mysql驱动、junit测试依赖-->
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

建立配置文件

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.jdbc.Driver"/>
                <!--配置url,&要用&amp转义-->
                <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <!--数据库用户名-->
                <property name="username" value="root"/>
                <!--数据库密码-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

</configuration>

创建sqlSession工具类

package com.mc10010.utils;

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

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "org/mybatis/example/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //创建sqlSession
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

创建POJO实体类

package com.mc10010.utils.pojo;
    /*
    * 创建User实体类
    * */
public class User {
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

创建dao接口

package com.mc10010.utils.dao;

import com.mc10010.utils.pojo.User;

import java.util.List;
    /*
    * 创建UserDao
    * */
public interface UserDao {
    List<User> getUserList();
}

编写配置类

<?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="com.mc10010.dao.UserDao">
    <!--执行的方法-->                <!--返回值类型-->
    <select id="getUserList" resultType="com.mc10010.pojo.User">
        select * from `test` where id = 1
    </select>
</mapper>

向注册中心注册UserDao

    <mappers>
        <mapper resource="com/mc10010/dao/UserDao.xml"/>
    </mappers>

配置导出设置

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>

            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

测试

import com.mc10010.dao.UserDao;
import com.mc10010.pojo.User;
import com.mc10010.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {
    @Test
    public void Test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User>  userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
}
结果:
User{id=1, name='雨看就'}

注意点

  • mapper没配置好

    org.apache.ibatis.binding.BindingException: Type interface com.mc10010.dao.UserDao is not known to the MapperRegistry.
  • 记得配置maven导出设置

        <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
    
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>

基本的CURD

查询 SELECT

    <!--select查询方式-->
    <!--执行的方法-->                <!--返回值类型-->
    <select id="getUserList" resultType="com.mc10010.pojo.User">
        select * from `test` where id = 1
    </select>
    <!--带变量的查询-->
    <select id="getUserById" resultType="com.mc10010.pojo.User" parameterType="int">
        SELECT * FROM `test` WHERE `id`=#{id}
    </select>
//编写接口
public interface UserDao {
    List<User> getUserList();
    User getUserById(int id);
}
//测试类
    @Test
    public void getUserByIdTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user1 = userDao.getUserById(2);
        System.out.println(user1);
        sqlSession.close();
    }
User{id=2, name='test '}

插入 INSERT

    <!--插入操作-->
    <insert id="insertUser" parameterType="com.mc10010.pojo.User">
        INSERT INTO `test`(id,name) value (#{id},#{name})
    </insert>
//接口
int insertUser(User user);
//测试
    @Test
    public void insertUserTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        int a = userDao.insertUser(new User(4,"李四"));
        sqlSession.commit();
        System.out.println(a);
    }
结果:
1

更新 UPDATE

    <!--更新操作-->
    <update id="updateUser" parameterType="com.mc10010.pojo.User">
        UPDATE `test` SET `name`=#{name} where `id`=#{id}
    </update>
//接口
int updateUser(User user);
//测试
    @Test
    public void updateUserTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        int a = userDao.updateUser(new User(4,"王五"));
        sqlSession.commit();
        System.out.println(a);
    }
结果:
1

删除 DELETE

    <!--删除操作-->
    <delete id="deleteUser" parameterType="int">
        DELETE FROM `test` WHERE `id`=1
    </delete>
//接口
int deleteUser(int id);
//测试
    @Test
    public void deleteUserTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        int a = userDao.deleteUser(1);
        sqlSession.commit();
        System.out.println(a);
    }
结果:
1
最后修改:2022 年 01 月 22 日
如果觉得我的文章对你有用,请随意赞赏