刚开始学习Mybatis可以先看下官方文档,MyBatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis避免了几乎所有的JDBC代码和手工设置参数以及抽取结果集。MyBatis使用简单的XML或注解来配置和映射基本体,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

下面进入正题:
工具:Navicat premium 、IntelliJ IDEA

简单的目录结构
在这里插入图片描述

1.创建mysql数据库
在这里插入图片描述
创建一个firend_mq数据库,建立一张表为 users ,并插入一些数据

2.新建一个maven项目,并导入依赖

 <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <!--添加mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!--jdbc驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--junit测试类-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.在resources文件夹下新建mybatis-config.xml,编写mybaits的核心配置文件

<?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核心配置文件-->
<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/firend_mq?useSSL=false&amp;useUnicode=&amp;characterEncodeing=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
<!--    注册mapper-->
    <mappers>
        <mapper resource="dao/UserMapper.xml"/>
    </mappers>
</configuration>

注意点:resource绑定mapper,需要使用路径,使用"/"
连接mysql数据库的时候可能会出现时区的问题,可以看这篇博客
idea连接mysql时区问题解决方案(永久)

4.编写mybatis工具类

//SqlSessionFactory
public class Mybatisutil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {//使用mybaatis第一步获取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 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句

    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

5.编写mybatis实体类

package pojo;

public class User {
    private int id;
    private String username;
    private String password;

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

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

前期的准备工作已完毕,开始编写代码

6.编写Dao层的接口

public interface UserDao {
    //查询所有用户
    List<User> getUserList();

    //查询指定id用户
    User getUserById(int id);

    //添加一个用户
    int addUser(User user);

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

    //删除一个用户
    int deleteUser(int id);
}

7.编写接口实现类
接口实现类由原来的UserDaoImpl转变为Mapper配置文件夹

<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="dao.UserDao">
<!-- select查询语句   -->
    <select id="getUserList" resultType="pojo.User">
        select * from firend_mq.users
    </select>
<!--    根据id查询-->
    <select id="getUserById" parameterType="int" resultType="pojo.User">
        select * from firend_mq.users where id = #{id}
    </select>

<!-- 添加一个用户   对象中的属性,可以直接取出去-->
    <insert id="addUser" parameterType="pojo.User">
        insert into firend_mq.users (id,username,password) value (#{id},#{username},#{password})
    </insert>

    <update id="updateUser" parameterType="pojo.User">
        update firend_mq.users set username=#{username},password=#{password}  where id=#{id};
    </update>

<!--    删除一个用户-->
    <delete id="deleteUser" parameterType="int">
        delete from firend_mq.users where id=#{id}
    </delete>
</mapper>

注意点:

  • Mapper配置文件一定要在mybatis-config.xml里面注册
  • 标签就是增删改查的类型,在标签里面书写原来的sql语句,使用#{}进行传值
  • namespace=绑定一个对应的Dao/Mapper接口,不要绑定错误的接口
  • id就是接口里面的方法名,要一致
  • parameterType是方法的参数类型,resultType是方法的返回值类型要对应接口。

8.编写测试类

public class UserDaoText {
    //查询所有用户
    @Test
    public void getUserList(){
        //第一步:获得sqlSession对象
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        //方式一:getMapper
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
//    查询指定id用户
    @Test
    public void getUserById(){
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
       User user = mapper.getUserById(2);
        System.out.println(user);
        sqlSession.close();
    }
    //所有的增删改都要提交事务
    //添加一个用户
    @Test
    public void addUser(){
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.addUser(new User(4,"张三","10086"));
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void updateUser(){
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.updateUser(new User(4,"哈哈","123"));
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteUser(){
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }

}

这样一个简单Mybatis的增删改查就写完了,细节都在代码中由注释。

posted on 2021-05-06 08:46  浪漫主义码农  阅读(450)  评论(0编辑  收藏  举报