Related configuration of mybatis project

Note: the development environment used is IDEA

  1. import dependency
    enter relevant dependency information in pom.xml
<!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

  • preparation of MyBatis core configuration file
    MyBatis config. XML
  • <!--核心配置文件-->
    <configuration>
    
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
    
        <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
        <mappers>
            <mapper resource="com/liu/mapper/UserMapper.xml"/>
        </mappers>
    
    </configuration>
    

    MyBatis tool class
    MybatisUtils

    package com.liu.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;
    
    /**
     * @author liucong
     * @date 2020/9/8 - 15:08
     */
    //sqlSessionFactory --> sqlSession
    public class MybatisUtils {
    
        private static SqlSessionFactory sqlSessionFactory;
    
        static{
            try {
                //使用Mybatis 第一步:获取sqlSessionFactory
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        public static SqlSession getSqlSession(){
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;
        }
    }
    
    1. create entity class
    package com.liu.pojo;
    
    /**
     * @author liucong
     * @date 2020/9/8 - 15:24
     */
    //实体类
    public class User {
        private int id;
        private String name;
        private String pwd;
    
        public User() {
        }
    
        public User(int id, String name, String pwd) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
        }
    
        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;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
                    '}';
        }
    }
    
    
    1. write Mapper interface class
    package com.liu.mapper;
    
    import com.liu.pojo.User;
    
    import java.util.List;
    
    /**
     * @author liucong
     * @date 2020/9/8 - 15:31
     */
    public interface UserMapper {
        //查询全部用户
        List<User> getUserList();
    
        //根据ID查询用户
        User getUserById(int id);
    
        //增加一个用户
        int addUser(User user);
    
        //修改用户
        int updateUser(User user);
    
        //删除一个用户
        int deleteUser(int id);
    }
    
    1. write mapper. XML configuration file
    <?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">
    <!--namespace:绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.liu.mapper.UserMapper">
        <select id="getUserList" resultType="com.liu.pojo.User">
            select * from user
        </select>
    
        <select id="getUserById" parameterType="int" resultType="com.liu.pojo.User">
            select * from mybatis.user where id=#{id}
        </select>
    
        <insert id="addUser" parameterType="com.liu.pojo.User">
            insert into mybatis.user (id, name, pwd) VALUES (#{id},#{name},#{pwd})
        </insert>
    
        <update id="updateUser" parameterType="com.liu.pojo.User">
            update mybatis.user set name = #{name},pwd=#{pwd} where id=#{id};
        </update>
    
        <delete id="deleteUser" parameterType="int">
            delete from mybatis.user where id=#{id}
        </delete>
    
    </mapper>
    
    1. write test class
    package com.liu.mapper;
    
    import com.liu.pojo.User;
    import com.liu.utils.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    /**
     * @author liucong
     * @date 2020/9/8 - 15:54
     */
    //org.apache.ibatis.binding.BindingException: Type interface com.liu.mapper.UserMapper is not known to the MapperRegistry.
    //java.lang.ExceptionInInitializerError
    public class UserMapperTest {
        @Test
        public void test(){
            //第一步:获得SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            //执行SQL
            //方式一:getMapper
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
    
            //方式二:
    //        List<User> userList = sqlSession.selectList("com.liu.mapper.UserMapper.getUserList");
    
            for(User user:userList){
                System.out.println(user);
            }
    
            //关闭SqlSession
            sqlSession.close();
        }
    
        @Test
        public void test2(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUserById(1);
            System.out.println(user);
    
            sqlSession.close();
        }
    
        //增删改需要提交事务
        @Test
        public void test3(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int res=mapper.addUser(new User(4,"王五","123456"));
            if(res>0){
                System.out.println("插入成功");
            }
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public void test4(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.updateUser(new User(4,"wangwu","1234"));
            sqlSession.commit();
    
            sqlSession.close();
        }
    
        public void test5(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.deleteUser(4);
            sqlSession.commit();
            sqlSession.close();
        }
    }
    

    possible problem note: Maven static resource filtering problem

    adds

    to the pom. XML file

    <!--在build中配置resources,来防止我们资源导出失败的问题-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    

    Read More: