mybatis详细教程

文章目录

    • @[toc]
    • 1. 概述
      • 1.1 什么是Mybatis?
      • 1.2 Mybatis 操作数据库的方式
      • 1.3 Mybatis 操作数据库的七大步骤?
      • 1.4 Mybatis 的开发优点
    • 2. Mybatis 操作数据库具体实现
      • 2.1 创建一个数据库表
      • 2.2 创建一个maven项目,配置pom.xml文件,导入相关依赖
      • 2.3 创建mybatis 核心配置文件
      • 2.4 创建与数据库对应的实体类
      • 2.5 创建数据操作持久层接口
      • 2.5-1 补充 创建数据操作持久层接口实现配置文件`UserMapper.xml`
      • 2.6 创建测试类,测试
      • 2.7 基于注解开发修改
      • 2.6 创建测试类,测试基于注解的mybatis开发
    • 运行结果

1. 概述

1.1 什么是Mybatis?

Mybatis 是一个优秀的持久层框架,是对JDBC操作数据库的过程进行了封装.

1.2 Mybatis 操作数据库的方式

  1. 可以通过xml文件的方式执行sql;
  2. 可以通过注解的方式执行SQL;

1.3 Mybatis 操作数据库的七大步骤?

  1. SQLSession 传递SQL骨架给MappedStatement
  2. 由MappedStatement 结合骨架和SQL参数映射成完整的SQL语句
  3. 将完整的SQL语句交给Executer
  4. 执行SQL语句
  5. 返回结果集给MappedStatement
  6. 封装结果集
  7. 将结果集返回给SQLSession

1.4 Mybatis 的开发优点

  1. 简化了JDBC代码
  2. 支持连接池,提高程序执行效率
  3. Mybatis 是将SQL配置在mapper文件中,修改SQL不需要重新编译
  4. 将返回结果ResultSet自动封装成java对象

2. Mybatis 操作数据库具体实现

  • 项目结构
    mybatis详细教程_第1张图片

2.1 创建一个数据库表

create database mytest;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '匿名',
  `age` int(11) NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '男',
  `address` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
  `email` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `email`(`email`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '匿名', 11, '男', '1111', '11111');

在这里插入图片描述

2.2 创建一个maven项目,配置pom.xml文件,导入相关依赖

mybatis详细教程_第2张图片


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.itgroupId>
    <artifactId>mybatis_leanartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.5version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.26version>
        dependency>
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.30version>
        dependency>
    dependencies>

project>

2.3 创建mybatis 核心配置文件

jdbc.properties文件,描述连接数据库的属性

jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mytest
jdbc.username = root
jdbc.password = 123456

mybatis-config.xml , mybatis 核心配置文件


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <properties resource="jdbc.properties"/>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    <environments default="test">
        <environment id="test">

            <transactionManager type="JDBC">transactionManager>

            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>

    <mappers>
        <mapper resource="mapper/UserMapper.xml">mapper>
    mappers>
configuration>
  • 注意:如果mapper/*.xml 报错,把*改成具体的mapper.xml文件名称,具体原因尚未明确

2.4 创建与数据库对应的实体类

package com.it.pojo;

public class User {
    private long id;
    private String name;
    private int age;
    private String sex;
    private String address;
    private String email;

    public User(long id, String name, int age, String sex, String address, String email) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.address = address;
        this.email = email;
    }

    public User() {
    }

    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

2.5 创建数据操作持久层接口

package com.it.dao;

import com.it.pojo.User;
import java.util.Collection;
@Mapper
public interface UserDao {
    Collection<User> findAll();
    User findById(long id);
    void save(User user);
    void update(User user);
    void delete(long id);
}

2.5-1 补充 创建数据操作持久层接口实现配置文件UserMapper.xml


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.it.dao.UserDao">
    <select id="findAll" resultType="com.it.pojo.User">
        select * from user
    select>

    <select id="findById" resultType="com.it.pojo.User">
        select * from user where id = #{id}
    select>

    <insert id="save">
        insert into user value(#{id},#{name},#{age},#{sex},#{address},#{email})
    insert>

    <update id="update">
        update user set name = #{name} where id = #{id}
    update>

    <delete id="delete">
        delete from user where id = #{id}
    delete>
mapper>

2.6 创建测试类,测试

package com.it.test;


import com.it.dao.UserDao;
import com.it.pojo.User;
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.util.Collection;

public class Test01 {
    static SqlSessionFactoryBuilder builder  =new SqlSessionFactoryBuilder();
    static  UserDao userDao;
    public static void findAll(){
        Collection<User> all = userDao.findAll();
        System.out.println("查询所有结果");
        System.out.println("---------------------------------");
        for (User user:all){
            System.out.println(user.toString());
        }
    }
    public static void findById(){
        User user = userDao.findById(1);
        System.out.println("查询所有结果");
        System.out.println("---------------------------------");
        System.out.println(user.toString());
    }

    public static void save(){
        User user = new User(3,"ls",22,"男","llll.","000000");
        userDao.save(user);
        System.out.println("新增数据"+user.toString()+"成功");
    }
    public static void update(){
        User user = new User(2,"zhangs",22,null,"","");
        userDao.update(user);
        System.out.println("修改数据"+user.toString()+"成功");
    }
    public static void delete(){
        userDao.delete(2);
        System.out.println("删除成功");
    }
    public static void main(String[] args) {
        SqlSession session=null;
        SqlSessionFactory factory = null;
        try {
            factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
            session = factory.openSession();
            userDao = session.getMapper(UserDao.class);
            System.out.println("============================");
            findAll();
            System.out.println("============================");
            findById();
            System.out.println("============================");
            save();
            findAll();
            System.out.println("============================");
            update();
            findAll();
            System.out.println("============================");
            delete();
            findAll();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (session!=null){
                session.commit();
                session.close();
            }
        }
    }
}

2.7 基于注解开发修改

修改dao层的代码,创建数据操作接口

package com.it.dao;

import com.it.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.Collection;

/**
 * 使用注解执行sql
 * @author ZRY
 * @version 1.0
 */
public interface UserDao1 {
    @Select("select * from user")
    Collection<User> findAll();
    @Select("select * from user where id = #{id}")
    User findById(long id);
    @Insert("insert into user value(#{id},#{name},#{age},#{sex},#{address},#{email})")
    void save(User user);
    @Update(" update user set name = #{name}  where id=#{id}")
    void update(User user);
    @Delete("delete from user where id=#{id}")
    void delete(long id);
}

修改核心配置文件,mybatis-config.xml
新增


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <properties resource="jdbc.properties"/>
    <environments default="test">
        <environment id="test">

            <transactionManager type="JDBC">transactionManager>

            <dataSource type="POOLED">
                <property name="dirver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>

    <mappers>
      
        <mapper resource="mapper/UserMapper.xml">mapper>

        <mapper class="com.it.dao.UserDao1"/>
    mappers>
configuration>

2.6 创建测试类,测试基于注解的mybatis开发

package com.it.test;


import com.it.dao.UserDao;
import com.it.dao.UserDao1;
import com.it.pojo.User;
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.util.Collection;

public class Test02 {
    static SqlSessionFactoryBuilder builder  =new SqlSessionFactoryBuilder();
    static UserDao1 userDao1;
    public static void findAll(){
        Collection<User> all = userDao1.findAll();
        System.out.println("查询所有结果");
        System.out.println("---------------------------------");
        for (User user:all){
            System.out.println(user.toString());
        }
    }
    public static void findById(){
        User user = userDao1.findById(1);
        System.out.println("查询所有结果");
        System.out.println("---------------------------------");
        System.out.println(user.toString());
    }

    public static void save(){
        User user = new User(2,"ls",22,"男","llll","");
        userDao1.save(user);
        System.out.println("新增数据"+user.toString()+"成功");
    }
    public static void update(){
        User user = new User(3,"zhangs",22,null,"","");
        userDao1.update(user);
        System.out.println("修改数据"+user.toString()+"成功");
    }
    public static void delete(){
        userDao1.delete(2);
        System.out.println("删除成功");
    }
    public static void main(String[] args) {
        SqlSession session=null;
        SqlSessionFactory factory = null;
        try {
            factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
            session = factory.openSession();
            userDao1 = session.getMapper(UserDao1.class);
            System.out.println("============================");
            findAll();
            System.out.println("============================");
            findById();
            System.out.println("============================");
            save();
            findAll();
            System.out.println("============================");
            update();
            findAll();
            System.out.println("============================");
            delete();
            findAll();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (session!=null){
                session.commit();
                session.close();
            }
        }
    }
}

运行结果

mybatis详细教程_第3张图片

你可能感兴趣的:(java全栈学习,mybatis,数据库,java)