mybatis快速入门

1、什么是mybatis?

mybatis核心对象: SqlSession
mybatis核心配置文件:mybatis-config.xml

mybatis 文件:
在这里插入图片描述

2、快速入门

环境:

  • JDK 17

  • mysql 8.0.3

  • maven 3.6

  • IDEA

1. 导入依赖

    <!--    导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

 <!--在build中配置resources,来防止我们资源导出失败的问题-->
    <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>

2. 根据数据库的表编写对应的实体类(pojo层)

public class User {
    private int id;
    private String name;
    private String pwd;
}
//有参构造、无参构造、get、set、方法省略..s

3. 编写核心配置文件

方式1:直接编写

<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration:-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--此处value增加时区设置代码即可-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
		<!-- 每一个mapper.xml都需要在mybatis核心配置文件中注册-->
        <mapper resource="com/smile/dao/UserMapper.xml"/>
    </mappers>
</configuration>

mysql 8.0 以上需要在数据库链接地址加上时区设置

<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;characterEncoding=UTF-8&amp;useUnicode=true&amp;serverTimezone=GMT"/>

**方式二:**通过外部配置文件

  1. 在resources文件内编写配置文件(此处我命名为:db.properties)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123
  1. 编写mybatis.config.xml文件
<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration:-->
<configuration>
    <!--1.引入外部配置文件-->
    <properties resource="db.properties"></properties>
    <!--给实体类创建别名-->
    <typeAliases>
        <typeAlias type="com.smile.pojo.User" alias="user"/>
    </typeAliases>

    <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.xml都需要在mybatis核心配置文件中注册-->
        <mapper resource="com/smile/dao/UserMapper.xml"/>
    </mappers>
</configuration>

在这里插入图片描述

4. 编写mapper接口 和mapper.xml (dao层)

mapper接口文件:(编写方法)

package com.smile.dao;

import com.smile.pojo.User;

import java.util.List;
import java.util.Map;

public interface UserMapper {
    //获取所有的用户
    List<User> getUserList();

    //根据id查询用户
    User getUserId(int id);

    //增加用户
    int addUser(User user);

    //使用Map增加用户
    int addUser2(Map<String,Object>map);

    //修改用户
    int UpdateUser(User user);

    //删除用户
    int DeleteUser(int id);

    //使用模糊查询
    List<User> getUserLike(String name);
    
}

mapper.xml文件:(编写具体的SQL操作)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace需要和对应的接口文件绑定-->
<mapper namespace="com.smile.dao.UserMapper">
    <!--id是接口文件里对应方法的名称,resultType是参数类型-->
    <select id="getUserList" resultType="com.smile.pojo.User">
       select * from mybatis.user
    </select>

    <select id="getUserId" parameterType="int" resultType="com.smile.pojo.User" >
        select * from mybatis.user where id = #{id}
    </select>

    <insert id="addUser" parameterType="com.smile.pojo.User">
        insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})
    </insert>

    <!--使用Map方式-->
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd}) ;
    </insert>

    <update id="UpdateUser" parameterType="com.smile.pojo.User">
        update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id}
    </update>

    <delete id="DeleteUser" parameterType="int">
        delete from mybatis.user where id = ${id}
    </delete>

	<!--模糊查询-->
    <!--resultType:返回值类型-->
    <select id="getUserLike" resultType="com.smile.pojo.User">
        select * from mybatis.user where name like '%${mame}%'  ;
    </select>
</mapper>

编写完mapper.xml后第一时间去mybatis-config.xml 核心配置文件中注册mapper!

    <mappers>
		<!-- 使用此方法 每一个mapper.xml都需要在mybatis核心配置文件中注册-->
       <!--单独加载某个指定的映射配置文件-->
        <mapper resource="com/smile/dao/UserMapper.xml"/>
    </mappers>

方法二:(此方法自定加载指包内的所有映射配置文件)

<mappers>
    <!--加载某包下所有的映射配置文件-->
    <package name="com.smile.dao"/>
</mappers>

5.编写工具类

在pojo同级文件夹内编写工具类 utils

package com.smile.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 {
    //提升作用域
    public  static SqlSessionFactory sqlSessionFactory ;
    static {
        try {
            // 核心配置文件classpath路径
            String resource = "mybatis-config.xml";
            // 加载配置文件
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 构建会话工厂
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //既然有了 sqlSessionFactory,顾名思义,我们就可以从中获得 SqLSession 的实例了。
    // sqLSession完全包含了面向数据库执行sQL命令所需的所有方法。
    public static SqlSession getSqlSession(){
            //openSession(true) :开启自动提交事务
        return  sqlSessionFactory.openSession(true);
    }

}

6. 测试

在text文件夹内建立同级的测试文件,建立测试类

package com.smile.dao;

import com.smile.pojo.User;
import com.smile.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserDaoTest {

    //获取用户
    @Test
    public void getUserList(){
        //1、使用工具类获取sqlSession 对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //2、执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();

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

        //关闭sqlSession
        sqlSession.close();
    }

    //通过用户id查询用户
    @Test
    public void getUserId(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userId = mapper.getUserId(2);
        System.out.println(userId);

        sqlSession.close();
    }

    //增加用户
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int xiaomi = mapper.addUser(new User(6, "Xiaomi3", "1232"));
        if (xiaomi > 0 ){
            System.out.println("插入成功!");
        }
        //提交事务
        sqlSession.commit();
        //关闭流
        sqlSession.close();
    }

    @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("name","xiaolu");
        map.put("pwd","123123");

        mapper.addUser2(map);

        sqlSession.commit();
        sqlSession.close();
    }

    //增加用户
    @Test
    public void UpdateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        int oppo = mapper.UpdateUser(new User(4, "OPPO", "122"));

        sqlSession.close();
    }

    //删除用户
    @Test
    public void DeleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        int i = mapper.DeleteUser(6);

        sqlSession.close();
    }

    //模糊查询用户
    @Test
    public void getUserLike(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> a = mapper.getUserLike("ao");
        for (User user : a) {
            System.out.println(user.toString());
        }

        sqlSession.close();
    }

}
    @Test
    public void getUserId(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userId = mapper.getUserId(2);
        System.out.println(userId);

        sqlSession.close();
    }

    //增加用户
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int xiaomi = mapper.addUser(new User(6, "Xiaomi3", "1232"));
        if (xiaomi > 0 ){
            System.out.println("插入成功!");
        }
        //提交事务
        sqlSession.commit();
        //关闭流
        sqlSession.close();
    }

    @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("name","xiaolu");
        map.put("pwd","123123");

        mapper.addUser2(map);

        sqlSession.commit();
        sqlSession.close();
    }

    //增加用户
    @Test
    public void UpdateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        int oppo = mapper.UpdateUser(new User(4, "OPPO", "122"));

        sqlSession.close();
    }

    //删除用户
    @Test
    public void DeleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        int i = mapper.DeleteUser(6);

        sqlSession.close();
    }

    //模糊查询用户
    @Test
    public void getUserLike(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> a = mapper.getUserLike("ao");
        for (User user : a) {
            System.out.println(user.toString());
        }

        sqlSession.close();
    }

}

getUserList 方法 测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值