• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

一、Mybatis简介和上手体验

开发技术 开发技术 4小时前 1次浏览

Mybatis官方中文文档:https://mybatis.org/mybatis-3/zh

1、简介

1.1、Mybatis是什么?

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的== XML 或注解==来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

1.2、Mybatis的特点

  • 简单易学
  • 灵活
  • 解除 SQL 与代码的耦合
  • 可实现 ORM 映射
  • 支持对象关系映射
  • 支持动态SQL

2、第一个Mybatis程序

思路:搭建环境–>导入Mybatis–>编写代码—>测试

2.1、环境搭建

搭建数据库

CREATE DATABASE mybatis;

USE mybatis;

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

INSERT INTO `user`(`id`, `name`, `pwd`) VALUES
(1, '张三', '123456'),
(2, '李四', '654321'),
(3, '王五', '111111')

创建一个maven项目,导入Mybatis和mysql、junit包

<dependencies>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
  </dependency>
</dependencies>

2.2、创建第一个模块

  • 编写mybatis核心配置文件

    在项目的resources下创建mybatis配置文件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/mybatis?useSSL=true&amp;useUnicodetrue&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="org/mybatis/example/BlogMapper.xml"/>
        </mappers>
    </configuration>
    
  • 在项目的utils包下创建MybatisUtils工具

    package com.luca.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;
    
    //SqlSessionFactory --> sqlSession
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            try {
                //使用Mybatis第一步:获取sqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = null;
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //既然有了sqlSessionFactory对象,顾名思义就可以使用它获取sqlSession对象了
        public static SqlSession getSqlSession() {
            return sqlSessionFactory.openSession();
        }
    }
    

2.3、编写代码

  • 实体类

    在pojo包下创建user表对应的实体类User

package com.luca.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;
    }
}
  • Dao接口

    在dao包下创建UserMapper接口

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

    又原来的Impl转变为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">
    <!--namespace绑定一个dao接口-->
    <mapper namespace="com.luca.dao.UserMapper">
        <!--id相当于重写方法的名字-->
        <select id="getUserList" resultType="com.luca.pojo.User">
            select * from mybatis.user;
        </select>
    </mapper>
    

截止目前,项目的结果如下,如果有没有说请清楚的地方可以参考下:

一、Mybatis简介和上手体验

2.4、测试

  • 在test中创建与java中对应的包路径,添加测试方法,点击运行会报错

    package com.luca.dao;
    
    import com.luca.pojo.User;
    import com.luca.utils.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    public class TestUserMapper {
        @Test
        public void test() {
            //第一步:获取sqlSession
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            //第二步:执行sql - 方式一
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user.getName());
            }
            System.out.println("==========");
            //第二步:执行sql - 方式二
            List<User> userList2 = sqlSession.selectList("com.luca.dao.UserMapper.getUserList");
            for (User user : userList2) {
                System.out.println(user.getName());
            }
    
            //关闭连接
            sqlSession.close();
        }
    }
    
  • 因为我们创建的UserMapper没有在mybatis-config.xml中注册,在配置文件中跟新mapper内容如下

    <mappers>
      <mapper resource="com/luca/dao/UserMapper.xml"/>
    </mappers>
    
  • 再次运行测试方法,发现还是报错,提示找不到资源(因为配置文件不在resources目录下)

    Caused by: java.io.IOException: Could not find resource com/luca/dao/UserMapper.xml
    	at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
    	at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
    	at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:376)
    	at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:120)
    	... 30 more
    

    遇到这种情况,需要在maven的配置中增加资源过滤的片段,如下:

    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
          </includes>
          <filtering>true</filtering>
        </resource>
        <resource>
          <directory>src/main/java</directory>
          <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
          </includes>
          <filtering>true</filtering>
        </resource>
      </resources>
    </build>
    
  • 我们清理下maven后重新运行下测试方法,发现sql语句可以正常查询了,输出了我们期望的数据

    Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
    张三
    李四
    王五
    ==========
    张三
    李四
    王五
    
    Process finished with exit code 0
    

程序员灯塔
转载请注明原文链接:一、Mybatis简介和上手体验
喜欢 (0)