我的第一个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>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>5.1.46version>
            dependency>
            
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatisartifactId>
                <version>3.5.5version>
            dependency>
            
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            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>
        <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>
         
        <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>
        <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&userUnicode=true&characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                dataSource>
            environment>
        environments>
        
        <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 selectUser();
    }
  • 接口实现

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    
    测试
    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 users = session.selectList("com.wong.mapper.UserMapper.selectUser");
            //方法二:
            UserMapper mapper = session.getMapper(UserMapper.class);
            List 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
代码文件位置图

我的第一个mybatis程序(含纠错)_第1张图片

常见报错
  • 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):

    核心配置文件中缺少:

    或者名称错误!

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

    在pom.xml中添加以下代码:

    
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>

你可能感兴趣的:(我的第一个mybatis程序(含纠错))