mybatis入门

官网:https://mybatis.org/mybatis-3/zh/getting-started.html

新建项目,在 pom.xml 文件中导包:mysql-connector-java + mabtis + junit

<dependencies>
   <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
   </dependency>
   <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
   </dependency>
   <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
   </dependency>
</dependencies>

删除src, 新建子模块 mybatis-01, 父级 pom 文件中会自动添加子模块<modules>,这样就不需要给每个子模块再重新导包了:

mybatis入门

resource文件夹添加 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="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/first&#95;sql?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="888888"/>
            </dataSource>
        </environment>
    </environments>

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

接口 UserMapper.java:

public interface UserMapper {
    List<User> getUserList();
}

接口实现文件  UserMapper.xml:

1. 绑定要实现的接口,

2. 指定:重写接口的方法、返回类型、sql 语句(最后不加分号)

3. 在 mybatis-config.xml 中注册

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace 绑定一个对应的Mapper接口-->
<mapper namespace="com.edward.dao.UserMapper">
    <select id="getUserList" resultType="com.edward.pojo.User">
        select * from first_sql.user
    </select>
</mapper>

pojo 实体类 User.java:  (一个实体类对应一张table数据表)

package com.edward.pojo;

public class User {
    private String name;
    private int age;
    private int salary;

    public User () {}

    public User (String name, int age, int salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public int getSalary() {
        return salary;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

工具类 

1. 用于读取 mybatis-config.xml 核心配置文件

2. 工具类中创建 SqlSession 对象 (用于读取实现类中的 sql 语句)

package com.edward.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 MybatisUtil {
    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 () {
        return sqlSessionFactory.openSession();
    }
}

MyTest 测试文件: 调用工具类中 getSqlSession 方法,读取实现类中的 sql 语句:

import com.edward.dao.UserMapper;
import com.edward.pojo.User;
import com.edward.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class MyTest {
    public static void main(String[] args) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();

        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userMapper.getUserList();

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

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭 SqlSession
            sqlSession.close();
        }
    }
}

执行结果:

mybatis入门

最终的目录结构:

mybatis入门

mybatis入门

【踩坑】:!!!!

报错:Could not find resource /mybatis-config.xml

mybatis入门

解决方法:在子模块的 pom 文件中加入:

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

报错:java.io.IOException: Could not find resource com.edward.dao.UserMapper.xml

原因:

mybatis入门

解决方法:把路径的点改为斜杠

mybatis入门

注意:xml 中属性值涉及到特殊符号要对字符进行转义

mybatis入门

上一篇:#进阶3:排序查询


下一篇:外部比较器