【MyBatis-01】搭建MyBatis

一、开发环境

  • IDE:idea 2020.3
  • 构建工具:maven 3.8.4
  • MySQL版本:MySQL 8.0.26
  • MyBatis版本:MyBatis 3.5.9

二、创建maven工程

补充:
新建empty project,在project中配置jdk,在setting中配置maven,新建module(maven)即可。

(1)打包方式:jar
(2)引入依赖:
	<dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
    </dependencies>
(3)创建MyBatis的核心配置文件

在resources目录下新建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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="111111"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <mapper resource="mappers/UserMapper.xml"/>
    </mappers>
</configuration>

可以使用jdbc.properties配置文件,在configuration中引入即可。

<properties resource="jdbc.properties"></properties>
(4)创建mapper接口

MyBatis中的mapper接口相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要提供实现类。

public interface UserMapper {
    //添加用户信息 
    int insertUser();
}

a. 在创建接口前先在数据库mybatis中创建表t_user
在这里插入图片描述

b. 创建普通java类User,用来接收用户信息

public class User {
    private Integer id;

    private String username;
    private String password;

    private Integer age;
    private String sex;
    private String email;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public User() {
    }

    public User(Integer id, String username, String password, Integer age, String sex, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
        this.sex = sex;
        this.email = email;
    }
}
(5)创建MyBatis的映射文件

mapper接口中是处理表的方法,一张表对应一个mapper接口,也对应一个映射文件,因此映射文件名一般与mapper接口保持一致(表所对应实体类类名+Mapper),且存放在resources的mappers目录下。

a. mapper接口

public interface UserMapper {
    /**
    * MyBatis面向接口编程的两个一致:
     * 1、映射文件的namespace要和mapper接口的全类名保持一致
     * 2、映射文件中SQL语句的id要和mapper接口中的方法名一致
     *
     * 表--实体类--mapper接口--映射文件
     **/
    /**
     * 添加用户信息
     */
    int insertUser();
}

b. 映射文件

找到处理表格操作的mapper接口文件,找到对应的处理方法,并编辑对应sql语句。

<?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">
<mapper namespace="cn.dhu.mybatis.mapper.UserMapper">
<!--    int insertUser();-->
    <insert id="insertUser">
        insert into t_user values(null,'admin','123445',23,'男','12345@qq.com')
    </insert>
</mapper>
(6)编写测试类testMyBatis
	@Test
    public void testMyBatis() throws IOException {
        //加载核心配置文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        //获取SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //获取sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        //获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取mapper接口对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //测试功能
        int result = mapper.insertUser();
        //提交事务
        sqlSession.commit();
        System.out.println("result:"+result);
    }

注意:

  1. 测试的时候可能报错,大概意思找不到mysql驱动,用网上的方法就可以,我的试过后没问题,重启一下idea就好。
  2. 删除功能、修改功能和添加功能测试方法一致。在mapper接口中写好对应方法名,在映射文件中配置好两个接口一致,在测试类中测试即可。
  3. 查询功能,需要返回类型,在配置文件中必须配置resultTyperesultMap。在测试类中测试即可
<!--    User getUserById();-->
    <!--
        查询功能的标签必须设置resultType或resultMap
        resultType:设置默认的映射关系
        resultMap:设置自定义的映射关系
    -->
    <select id="getUserById" resultType="cn.dhu.mybatis.pojo.User">
        select * from t_user where id = 4;
    </select>

<!--    List<User> getAllUsers();-->
    <select id="getAllUsers" resultType="cn.dhu.mybatis.pojo.User">
        select * from t_user
    </select>

本文主要参考:
【尚硅谷】2022版MyBatis教程(细致全面,快速上手)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值