第一个Mybatis

第一个Mybatis

思路:搭建环境-->导入Mybatis-->编写代码-->测试

1、搭建环境

新建maven工程,配置xml文件

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

    <!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--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>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
  • 编写mybatis的核心配置文件(在resources文件夹下创建mybatis-config.xml)
    Mysql8.0以上url还得设置时区setTimeZone
<?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核心配置文件-->
<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;characterEncode=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--每一个Mapper.xml都需要在mybatis核心配置文件中注册!-->
    <mappers>
        <mapper resource="org/mybatis/example/UserDaoMapper.xml"/>
    </mappers>
</configuration>

2、编写代码

  • 实体类

    package com.spong.pojo;
    
    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 + '\'' +
                    '}';
        }
    }
    
  • Mapper接口

    public interface UserMapper {
        List<User> getUserList();
    }
    
  • 接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件 UserMapper.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">
    
    <!--namespace绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.spong.dao.UserDao">
        <select id="getUserList" resultType="com.spong.pojo.User">
            select * from mybatis.user
        </select>
    </mapper>
    
  • MybatisUtils工具类

    将sqlSessionFactory的创建以及获取SqlSession的方法封装为工具类,实际请求中使用MybatisUtils工具类的静态方法直接获得SQLSession实例。

    package com.spong.util;
    
    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 {
    
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            try {
                //获取SqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //获取SQLSession实例,SQLSession中完全包含了面向数据库执行SQL命令所需的所有方法
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    
    }
    

3、测试

junit测试

@Test
public void test(){
    //第一步,获取SqlSession对象
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    //第二步,执行sql
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = mapper.getUserList();

    for (User user : userList) {
        System.out.println(user);
    }

    //关闭SqlSession
    sqlSession.close();
}

异常:org.apache.ibatis.binding.BindingException: Type interface com.spong.dao.UserDao is not known to the MapperRegistry.

需要在核心配置文件中注册mappers

<!--每一个Mapper.xml文件都要在核心配置文件中注册-->
    <mappers>
        <mapper resource="com/spong/dao/UserMapper.xml"/>
    </mappers>

maven资源导出问题(测试时发现mybatis.xml文件未找到):

需要在pom.xml中配置

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

如有错误,欢迎大佬指正!

posted @ 2020-08-09 22:00  想拥有两颗❤  阅读(102)  评论(0编辑  收藏  举报