关于mybatis的使用,这篇文章能解决你90%的问题

77 阅读3分钟

1. Mybatis

1.1 mybatis 介绍

MyBatis是一款开源的Java持久层框架。它通过XML或注解的方式将要执行的SQL语句与Java对象进行映射,封装了JDBC操作,可以轻松地与数据库交互。MyBatis可以使用简洁的语法实现复杂的查询和多表关联查询,同时支持动态SQL,可根据不同的条件生成不同的SQL语句。

MyBatis与传统的ORM框架不同的是,它将SQL语句和Java对象进行映射,同时提供了强大的灵活性和扩展性,可以根据自己的需要定义SQL语句,也可以使用自定义的Java类型处理器和类型转换器实现更复杂的映射逻辑。

另外,MyBatis还支持事务控制、缓存管理和插件扩展等功能,可以大大提高应用程序的可维护性和性能。由于其简单易用、灵活可扩展的特性,MyBatis在企业级应用中广泛应用。

1.2 mybatis下载地址

github.com/mybatis/myb…

image.png

2. 搭建MyBatis

2.1 加入依赖

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>

2.2 MyBatis的配置文件

spring: 
    datasource: 
        url: jdbc:mysql://localhost:3306/mydb 
        username: myuser 
        password: mypassword 
        driver-class-name: com.mysql.jdbc.Driver

2.3 创建mybatis的映射文件

相关概念:ORM(Object Relationship Mapping)对象关系映射。

  • 对象:Java的实体类对象
  • 关系:关系型数据库
  • 映射:二者之间的对应关系 image.png
  1. 映射文件的命名规则: 表所对应的实体类的类名+Mapper.xml
  • 例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml*
  • MyBatis映射文件用于编写SQL,访问以及操作表中的数据
  • MyBatis映射文件存放的位置是src/main/resources/mappers目录下

2.MyBatis中可以面向接口操作数据,要保证两个一致:

  • mapper接口的全类名和映射文件的命名空间(namespace)保持一致
  • mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致

3.Mybatis如何实现CRUD

这里的数据库准备用mybatis-plus的相关素材mybatisplusjoin.com/pages/quick…

3.1 创建数据及插入数据

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id    BIGINT(20) NOT NULL COMMENT '主键ID',
    name  VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age   INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);

3.2 数据库前提准备

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

@Data
public class UserDto {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}    

3.3 编写UserMappe.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="com.cx.model.dao.UserMapper">  
    <resultMap id="BaseResultMap"  
    type="com.cx.model.dao.UserMapper">  
        <id column="id" jdbcType="BIGINT" property="id"/>  
        <result column="name" jdbcType="VARCHAR" property="name"/>  
        <result column="age" jdbcType="SMALLINT" property="age"/>  
        <result column="email" jdbcType="VARCHAR" property="email"/>  
    </resultMap> 
    
    <sql id="Base_Column_List">  
    id, name, age, email 
    </sql>
    </resultMap>
</mapper>

3.4 查询语句

3.4.1 selectUser

<!--long selectUserById();-->
<select id="selectUserById", parameterType="java.lang.Long", resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from
    user
    where id=#{id, jdbcType="BIGINT"}    
</select>

3.4.2 selectByCondition

此处有必要介绍一下@param注解,在Mybatis的mapper文件中,@param注解使用方法类似于Java代码中的文档注释。通常,它被用于SQL语句中的参数。

例如,考虑一个简单的Mapper接口,其中定义了一个查询方法,用来查询某个特定用户的信息。可以使用如下方式来在mapper文件中使用@param注解:

<select id="selectUserById" resultType="User">
    select * from user where id=#{id, jdbcType=INTEGER}
</select>

在这个例子中,查询方法的名称是selectUserById,它的输入参数为一个整数类型的id。为了让Mybatis正确地将id参数传递给SQL查询语句中的占位符,使用了#{id}来代替id参数。此外,也使用了@param注解来更详细地描述该参数:

  • id: 参数的名称。
  • jdbcType=INTEGER: 指定在将参数传递给SQL语句时,要使用的JDBC类型。

使用@param注解的好处是可以减少错误和混淆,尤其是在方法中有多个参数或者参数类型比较复杂时更为实用。同时,它也可以方便地阅读和维护SQL语句。

重要的@param输入之后,不需要输入paramType

public interface UserMapper {
    User selectByCondition(@Param("condition") UserDto userDto);
}
<!--long selectByCondition();-->
<sql id="where_Condition">
    <where>
        <if test="condition.id != null">
            and id=#{condition.id}
        </if>
        <if test="condition.name != null">
            and nam=#{condition.name}
        </if>
        <if test="condition.age != null">
            and id=#{condition.age}
        </if>
        <if test="condition.email != null">
            and id=#{condition.id}
        </if>
     </where>   
</sql>    

<select id="selectByCondition", resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List"/>
    from
    user
    where <include refid="where_Condition"/>
</select>