我的第一个mybatis程序(含纠错)

我的第一个mybatis程序

编写一个mybatis程序的主要流程:

  • 搭建需要的环境

  • 导入相关jar包

  • 编写代码

  • 运行测试

搭建环境
使用MySQL数据库

创建一个表名为mybatis,写入几行数据,具体代码如下:

CREATE DATABASE `mybatis`;      //新建数据库
​
USE `mybatis`;
CREATE TABLE `user`(            //创建表
    `id` INT(20) NOT NULL,
    `name` VARCHAR(30) DEFAULT NULL,
    `pwd` VARCHAR(30) DEFAULT NULL,
    PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
​
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES        //写入数据
(1,'hayden','9918'),
(2,'wong','8899'),
(3,'jane','123456')

创建项目

  • 新建一个普通的maven项目

  • 删除该项目下的src目录,使其成为一个父工程(方便之后进行在父工程下创建子工程)

  • 在pom.xml中导入依赖(MySQL驱动、mybatis、junit)

     <!--导入依赖-->
        <dependencies>
            <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.46</version>
            </dependency>
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.5</version>
            </dependency>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
创建一个模块
  • 在之前的父工程下创建一个模块(本子模块就可以使用原来父工程的pom.xml中导入的jar包)

  • 配置核心配置:在新建的子工程目录下的src/main/resourses目录下新建文件: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核心配置文件-->
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
        </environments>
         <!--每一个mapper.xml都需要在mybatis.xml的核心配置文件中注册-->
        <mappers>
            <mapper resource="com.wong.dao.UserMapper.xml"/>
        </mappers>
    </configuration>

    将其中的value值修改为我们需要的:

    <?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=false&amp;userUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <!--每一个mapper.xml都需要在mybatis.xml的核心配置文件中注册-->
        <mappers>
            <mapper resource="com.wong.dao.UserMapper.xml"/>
        </mappers>
    </configuration>
  • 编写mybatis工具类(在java目录下创建包Utils,创建类MybatisUtils,使用sql语言时就需要用到这个工具类)

    package com.wong.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 {
        private static SqlSessionFactory sqlSessionFactory;
        static {
            try {
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //获取SqlSession连接
        public static SqlSession getSession(){
            return sqlSessionFactory.openSession();
        }
    }
编写代码
  • 数据库相关实体类

    package com.wong.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 + '\'' +
                    '}';
        }
    }
  • Dao接口

    package com.wong.dao;
    ​
    import com.wong.pojo.User;
    ​
    import java.util.List;
    ​
    public interface UserMapper {
        List<User> selectUser();
    }
  • 接口实现

    <?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.wong.dao.UserMapper"><select id="selectUser" resultType="com.wong.pojo.User">
        select * from user
      </select></mapper>
    测试
    package com.wong.dao;
    import com.wong.pojo.User;
    import com.wong.utils.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    import java.util.List;
    public class MyTest {
        @Test
        public void selectUser() {
            SqlSession session = MybatisUtils.getSession();
            //方法一:
            //List<User> users = session.selectList("com.wong.mapper.UserMapper.selectUser");
            //方法二:
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> users = mapper.selectUser();
            for (User user: users){
                System.out.println(user);
            }
            session.close();
        }
    }

    得到结果:

    User{id=1, name='hayden', pwd='9918'}
    User{id=2, name='wong', pwd='8899'}
    User{id=3, name='jane', pwd='123456'}
    ​
    Process finished with exit code 0
代码文件位置图

常见报错
  • org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. 异常解决

    完整的url的value如下: jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8

  • org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

    核心配置文件中缺少:

    <mappers> <mapper resource="com.wong.dao.UserMapper.xml"/> </mappers>

    或者名称错误!

  • java.lang.ExceptionInInitializerError //初始化异常

    在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-07-12 15:55  HaydenWong211  阅读(218)  评论(0编辑  收藏  举报