MyBatis使用教程详解

文章目录

  • MyBatis
  • 一、入门案例
  • 二、基础sql(增删改查)
    • 1.insert
    • 2.delete
    • 3.update
    • 4.select
    • 5.标签与参数
  • 三.核心配置文件
  • 四.mapper代理开发
  • 五.复杂sql
    • 1.主键返回
    • 2.动态sql
    • 3.批量操作
    • 4.表的关联


MyBatis

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。


一、入门案例

步骤如下:
1.建库建表
2.创建maven项目
3.修改pom文件,添加依赖
4.创建核心配置文件SqlMapConfig.xml
5.创建实体类
6.创建mapper映射文件
7.测试

具体演示
1.建库建表
ssm数据库,student表
MyBatis使用教程详解_第1张图片
MyBatis使用教程详解_第2张图片

2.在idea中创建maven项目
MyBatis使用教程详解_第3张图片

MyBatis使用教程详解_第4张图片
MyBatis使用教程详解_第5张图片

3.修改pom文件,添加依赖
在pom.xml中添加依赖

<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

4.创建核心配置文件SqlMapConfig.xml
在src/main/resources下创建SqlMapConfig.xml文件,打开mybatis官网

https://mybatis.net.cn/getting-started.html

在入门文档中复制配置文件,粘贴到SqlMapConfig.xml文件中,并且配置数据源

MyBatis使用教程详解_第6张图片

MyBatis使用教程详解_第7张图片

<?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/ssm?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>

5.创建实体类
创建Student类

package com.hem.pojo;

public class Student {
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }

    public Student(String name, String email, Integer age) {
        this.name = name;
        this.email = email;
        this.age = age;
    }

    public Student(Integer id, String name, String email, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }

    public Student() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

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

    public Integer getAge() {
        return age;
    }

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


MyBatis使用教程详解_第8张图片

6.创建mapper映射文件
在resources下创建StudentMapper.xml文件,在mybatis官网入门文档下复制xml映射文件,并粘贴到StudentMapper.xml中
并编写sql语句:select name,email,age from student where id = #{id}
还要在SqlMapConfig.xml文件中加载StudentMapper.xml

MyBatis使用教程详解_第9张图片

StudentMapper.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">
<mapper namespace="StudentMapper">
    <select id="getById" parameterType="int" resultType="com.hem.pojo.Student">
        select name,email,age from student where id = #{id}
    </select>
</mapper>

SqlMapConfig.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/ssm?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

7.测试
过程:
使用文件流读取核心配置文件SqlMapConfig.xml,
创建SqlSessionFactory工厂,
取出sqlSession对象,
完成查询操作,
关闭sqlSession

package com.hem.test;

import com.hem.pojo.Student;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class test1 {
    @Test
    public void testGetById() throws IOException {
        //使用文件流读取核心配置文件SqlMapConfig.xml
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //完成查询操作
        Student student = sqlSession.selectOne("StudentMapper.getById",1);
        System.out.println(student);
        //关闭sqlSession
        sqlSession.close();
    }
}

测试结果:
MyBatis使用教程详解_第10张图片

二、基础sql(增删改查)

先给出增删改查语句,再说明标签及参数

1.insert

使用< insert >标签

    <insert id="insert" parameterType="com.hem.pojo.Student">
        insert into student (name,email,age)
        values (#{name},#{email},#{age});
    </insert>

测试:

    @Test
    public void testInsert() throws IOException {
        //使用文件流读取核心配置文件SqlMapConfig.xml
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //完成查询操作
        int num = sqlSession.insert("StudentMapper.insert",new Student("小白","12321",99));
        System.out.println(num);
        sqlSession.commit();
        //关闭sqlSession
        sqlSession.close();
    }

测试结果:
MyBatis使用教程详解_第11张图片

MyBatis使用教程详解_第12张图片

2.delete

使用< delete >标签

    <delete id="delete" parameterType="int" >
        delete from student
        where id = #{id};
    </delete>

测试:

    @Test
    public void testDelete() throws IOException {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
        int num = sqlSession.delete("StudentMapper.delete",6);
        System.out.println(num);
        sqlSession.commit();
        sqlSession.close();
    }

测试结果:
MyBatis使用教程详解_第13张图片

MyBatis使用教程详解_第14张图片

3.update

使用< update >标签

    <update id="update" parameterType="com.hem.pojo.Student">
        update student
        set name = #{name} ,email = #{email},age = #{age}
        where id = #{id};
    </update>

测试:

    @Test
    public void testUpdate() throws IOException {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
        int num = sqlSession.update("StudentMapper.update",new Student(5,"小刘","1",99));
        System.out.println(num);
        sqlSession.commit();
        sqlSession.close();
    }

测试结果:
MyBatis使用教程详解_第15张图片

MyBatis使用教程详解_第16张图片

4.select

使用< select >标签
4.1按主键id查询

    <select id="getById" parameterType="int" resultType="com.hem.pojo.Student" >
        select id,name,email,age
        from student
        where id=#{id};
    </select>

4.2查询全部

    <select id="getAll" resultType="com.hem.pojo.Student" >
        select id,name,email,age
        from student;
    </select>

测试:

    @Test
    public void testSelectAll() throws IOException {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
        List<Student> list = sqlSession.selectList("StudentMapper.getAll");
        for (Student student : list){
            System.out.println(student);
        }
        sqlSession.close();
    }

测试结果:
MyBatis使用教程详解_第17张图片

4.3模糊查询

    <select id="getByName" parameterType="string" resultType="com.hem.pojo.Student">
        select id,name,email,age
        from student
        where name like '%${name}%';
    </select>

5.标签与参数

5.1namespace: mybatis中为每一个映射文件添加一个namespace,这样不同的映射文件中sql语句的id相同也不会有冲突,只要定义在映射文件中的sql语句在该映射文件中id唯一就可以

5.2标签的id.在本xml文件中的唯一标识

5.3有入参,用parameterType,并填写类型

5.4有返回值resultType,并填写类型

5.5#{}表示一个占位符号 相当于 jdbc中的 ? 符号
将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号
只有一个参数时可以参数名称随便写

5.6${}:为拼接符,即字符串拼接

三.核心配置文件

点击进入—MyBatis的核心配置文件详情

四.mapper代理开发

点击进入----mapper代理开发详情

五.复杂sql

1.主键返回

点击进入----主键返回详情

2.动态sql

点击进入----动态sql详情

3.批量操作

4.表的关联

202210152136

你可能感兴趣的:(MyBatis,mybatis,java,maven)