2、第一个Mybatis程序(容易出错的地方)

思路:

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

 

 

一、搭建环境

  1、搭建数据库:

CREATE DATABASE `mybatis`;

USE mybatis;

CREATE TABLE `user` (
    `id` INT (20) NOT NULL,
    `name` VARCHAR (30),
    `pwd` VARCHAR (30),
    PRIMARY KEY (`id`)
) ENGINE = INNODB DEFAULT CHARSET = utf8;

INSERT INTO `USER`
VALUES
    (1, 'zhangsan', '123'),
    (2, 'lisi', '1234'),
    (3, 'wangwu', '12345'),
    (4, 'zhixi', 'zhixi158');

  2、创建Maven:

  1. 创建一个空的maven(不选择模板)
  2. 删除src目录(为了使当前.pom.xml是父工程)
  3. 在idea设置中将maven仓库以及配置文件地址改为自己的
  4. pom.xml所需依赖
    <dependencies>
        <!--junit注解依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <!--mysql-jdbc依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
    </dependencies>

  3、新建模块

  1. 新建一个模块,这样就可以使用在父模块中的pom.xml了
  2. 在resouces下新建mybatis-config.xml文件,下面是配置文件代码,注意修改成自己的mysql账号密码
<?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"/>
                <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="zhixi158"/> </dataSource> </environment> </environments> </configuration>

 

        

 

二、编写代码

 1、封装工具类:下面是官方给的代码,我们来进行一个封装

 

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 zhangzhixi
 */
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //1、使用mybatis第一步,获取SQL会话工厂对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //2、创建能执行SQL的对象
    public static SqlSession getSqlSession() {
        //sqlSessionFactory返回的对象"SqlSession"表示JDBC中的Connection
        return sqlSessionFactory.openSession();
    }
}

  2、 编写实体类User

package com.zhixi.pojo;

/**
 * @author zhangzhixi
 */
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 + '\'' +
                '}';
    }
}

  3、dao层实体类接口

 

public interface IUserDao {
    /**
     * @return
     */
    List<User> getUserList();
}

 

   4、接口实现类:接口实现类由原来的IUserDaoImpl转变为一个.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">

<!--命名空间:绑定UserDao相当于实现这个接口-->
<mapper namespace="com.zhixi.dao.IUserDao">
    
    <!--不需要再写接口的实现类,在配置文件里写sql即可-->
    <!--id相当于重写接口的实现类-->
    <select id="getUserList" resultType="com.zhixi.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

 

三、测试

使用junit编写测试类:

package com.zhixi.Dao;

import com.zhixi.dao.IUserDao;
import com.zhixi.pojo.User;
import com.zhixi.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class IUserDaoTest {
    @Test
    public void test() {
        //1、获取SQLSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        
        IUserDao userDao = sqlSession.getMapper(IUserDao.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }

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

1、错误:org.apache.ibatis.binding.BindingException: Type interface com.zhixi.dao.IUserDao is not known to the MapperRegistry.

说没有指定配置文件位置找不到:在mybatis-config.xm中添加对应路径;

 

 2、出现错误:ExceptionInInitializerError:初始化错误

还是找不到UserMapper.xml文件,这是Maven的问题,添加以下代码到pom.xml中:

======================================================================================================================================

解决方法1:

  把实体类UserMapper.xml放到resources目录下,让资源能够被找到,同时注意修改mybatis-config.xml中的路径

 

======================================================================================================================================

 解决方法2:

在pom.xml中添加以下代码,让程序能够找到资源:

需要注意:这个代码需要添加在当前项目和父项目的pom.xml中(为了保险)

 <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>

 

成功运行:

 

posted @ 2020-12-26 23:41  Java小白的搬砖路  阅读(289)  评论(0编辑  收藏  举报