MyBatis学习笔记——02第一个Mybatis程序

一. 搭建环境

1. 创建数据库
  1. sql语句

    # 创建表
    create database mybatis;
    use mybatis;
    
    create table people(
    	id int(10) primary key,
    	name varchar(16) default null,
    	pwd varchar(32) default null
    )engine=innodb default charset=utf8;
    
    # 插入数据
    insert into people(id, name, pwd) values
    	(1, "people1", "123456"),
    	(2, "people2", "123456"),
    	(3, "people3", "123456"),
    	(4, "people4", "123456"),
    	(5, "people5", "123456"),
    	(6, "people6", "123456"),
    	(7, "people7", "123456"),
    	(8, "people8", "123456")
    
  2. 结果
    MyBatis学习笔记——02第一个Mybatis程序_第1张图片

2. 创建maven项目
  1. 新建一个普通的maven项目
  2. 删除src目录
  3. 导入maven依赖
    <dependencies>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
        
        
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.2version>
        dependency>
    
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
    dependencies>
    

二. 创建一个maven模块

1. 编写mybatis的核心配置文件(mybatis-config.xml)
  • 配置
    
    
    
    <configuration>
    
    
        
        <environments default="test">
    
            <environment id="test">
                <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&useUnicode=true&characterEncoding=utf-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                dataSource>
            environment>
        environments>
    
        
        <mappers>
            <mapper resource="com/hjf/dao/PeopleMapper.xml"/>
        mappers>
    configuration>
    
    
2. 编写mybatis的工具类(MybatisUtils)
  • 代码
    package com.hjf.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;
    
    /**
     * @author Jiang锋时刻
     * @create 2020-08-14 12:30
     */
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory = null;
        static {
            try {
                // 1. 获取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() {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;
        }
    }
    

三. 编写代码

1. 根据数据库表中的字段创建实体类(People)

现在严格按照列名创建属性名

  • 代码

    package com.hjf.pojo;
    
    /**
     * @author Jiang锋时刻
     * @create 2020-08-16 17:21
     */
    public class People {
        private int id;
        private String name;
        private String pwd;
    
        public People() {
        }
    
        public People(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 + '\'' +
                    '}';
        }
    }
    
2. 创建Dao接口(PeopleMapper)
  • 代码

    package com.hjf.dao;
    import com.hjf.pojo.People;
    import java.util.List;
    public interface PeopleMapper {
        /**
         * 获取人员信息列表
         * @return
         */
        List<People> getPeopleList();
    }
    
3. 创建一个与Dao接口同名的配置文件(PeopleMapper.xml)

接口实现类由原来的PeopleDaoImpl转变为一个 Mapper配置文件.

  1. 代码

    
    
    
    
    
    <mapper namespace="com.hjf.dao.PeopleMapper">
        
        <select id="getPeopleList" resultType="com.hjf.pojo.People">
            select * from people
        select>
    mapper>
    
  2. 注意

    1. 创建的每一个配置文件都需要在核心配置文件中注册 mappers

      <mappers>
        <mapper resource="com/hjf/dao/PeopleMapper.xml"/>
      mappers>
      

      MyBatis学习笔记——02第一个Mybatis程序_第2张图片

    2. 如果未引入会报如下错误

      org.apache.ibatis.binding.BindingException: Type interface com.hjf.dao.PeopleMapper is not known to the MapperRegistry.MyBatis学习笔记——02第一个Mybatis程序_第3张图片

4. 创建测试类
  • 代码
    package com.hjf.dao;
    
    import com.hjf.pojo.People;
    import com.hjf.utils.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    /**
     * @author Jiang锋时刻
     * @create 2020-08-16 19:13
     */
    public class PeopleMapperTest {
        @Test
        public void testGetPeopleList() {
            // 1. 获得sqlSession的对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            // 方式1: getMapper
            PeopleMapper mapper = sqlSession.getMapper(PeopleMapper.class);
            List<People> peopleList = mapper.getPeopleList();
    
            // 方法2:
            // List peopleList = sqlSession.selectList("com.hjf.dao.PeopleMapper.getPeopleList");
            
            for (People people : peopleList) {
                System.out.println(people);
            }
            
            // 关闭资源
            sqlSession.close();
        }
    }	
    

说明:

  1. 本文参考了狂神的Mybatis的课件
  2. 课程链接

你可能感兴趣的:(Mybatis,mybatis)