Mybatis学习

什么是Mybatis?

看官网的定义:

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

分析一下,mybatis是一种框架,它的用处是来做我们平常说的dao层的,重要的是,它是一种半自动化的框架,可以完成对JDBC和对数据库的CRUD操作的封装,可以很大程度地简化我们开发工作。 

再来看他是如何工作的:

先导入依赖

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

  我在pom.xml中的依赖导入:

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

  首先来看最基本的配置文件:

官方的配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <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 resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

  我们在用的时候应该修改的地方,在<environments>标签上添加数据库连接基本配置信息。

<properties resource="jdbc.properties"></properties>

  mybatis的事务管理的类型是JDBC的,所以待会进行对数据库的CRUD操作时不要忘记完成对事务的提交,否则就会发生事务的回滚。然后修改<mappers>标签中的内容。在进行这一步时你首先要知道mapper是什么?

  mapper就是一种映射器,里面内容是映射文件的所在位置,将

 <mapper resource="org/mybatis/example/BlogMapper.xml"/>修改你存放mapper.xml文件的位置

例如我这里将mapper.xml文件都放到一个包下了

<package name="com.rsh.spring.mapper"/>

 

,而这些映射文件就是你对数据库封装你对数据库进行CRUD代码的,先来看一个BrandMapper.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.rsh.spring.mapper.BrandMapper">

    <resultMap id="BaseResultMap" type="com.rsh.spring.pojo.Brand">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="brandName" column="brand_name" jdbcType="VARCHAR"/>
            <result property="companyName" column="company_name" jdbcType="VARCHAR"/>
            <result property="ordered" column="ordered" jdbcType="INTEGER"/>
            <result property="description" column="description" jdbcType="VARCHAR"/>
            <result property="status" column="status" jdbcType="INTEGER"/>
    </resultMap>

    <sql id="Base_Column_List">
        id,brand_name,company_name,
        ordered,description,status
    </sql>

    <select id="selectAll" resultMap="BaseResultMap">
        select * from tb_brand
    </select>
    <select id="selectById" resultMap="BaseResultMap">
        select *
        from tb_brand where id = #{id};
    </select>
<!--    <select id="selectByCondition" resultMap="BaseResultMap">-->
<!--        select *-->
<!--        from tb_brand-->
<!--        where status = #{status}-->
<!--        and brand_name like #{brandName}-->
<!--        and company_name like #{companyName};-->
<!--    </select>-->
    <select id="selectByCondition" resultMap="BaseResultMap">
        select *
        from tb_brand
        <where>
            <if test="status != null">
                status = #{status}
            </if>
            <if test="companyName != null and companyName != ''">
                and company_name like #{companyName}
            </if>
            <if test="brandName != null and brandName != ''">
                and brand_name like #{brandName};
            </if>
        </where>
    </select>

    <select id="selectByConditionSingle" resultMap="BaseResultMap">
        select *
        from tb_brand
        <where>
            <choose>
                <when test="status != null">
                    status = #{status}
                </when>
                <when test="companyName != null and companyName != ''">
                    and company_name like #{companyName}
                </when>
                 <when test="brandName != null and brandName != ''">
                 and brand_name like #{brandName}
                </when>
            </choose>
        </where>
    </select>

    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into tb_brand (brand_name, company_name, ordered, description, status)
        values (#{brandName},#{companyName},#{ordered},#{description},#{status})
    </insert>
<!--    <update id="update">-->
<!--        update tb_brand-->
<!--        set brand_name =#{brandName},-->
<!--            company_name =#{companyName},-->
<!--            description = #{description},-->
<!--            status = #{status},-->
<!--            ordered =#{ordered}-->
<!--        where id =#{id}-->
<!--    </update>-->
    <update id="update">
        update tb_brand
        <set>
            <if test="companyName != null and companyName != ''">
                company_name =#{companyName},
            </if>
            <if test="brandName != null and brandName != ''">
                brand_name =#{brandName},
            </if>
            <if test="description != null and description != ''">
                description = #{description},
            </if>
            <if test="status != null">
                status = #{status},
            </if>
            <if test="ordered != null">
                ordered =#{ordered}
            </if>
        </set>
        where id =#{id};
    </update>
    <delete id="deleteById">
        delete from tb_brand where id = #{id}
    </delete>
    <delete id="deleteByIds">
        delete from tb_brand where id
        in
            <foreach collection="ids" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        ;
    </delete>
</mapper>

这里面的代码就是对tb_brand表进行的CRUD,有添加,修改,删除,还有多条件,以及多条件和单条件的动态查询。

我们再来看对应的java代码

package com.rsh.spring.mapper;

import com.rsh.spring.pojo.Brand;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;

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

/**
* @author 15251
* @description 针对表【tb_brand】的数据库操作Mapper
* @createDate 2022-09-28 08:46:29
* @Entity com.rsh.spring.pojo.Brand
*/
@Component
public interface BrandMapper {

     List<Brand> selectAll();

     Brand selectById(int id);

     List<Brand> selectByCondition(@Param("status")int status,@Param("brandName")String brandName,@Param("companyName")String companyName);

     List<Brand> selectByCondition(Brand brand);

     List<Brand> selectByCondition(Map map);

    List<Brand> selectByConditionSingle(Map map);

    void add(Brand brand);

    int update(Brand brand);

    void deleteById(int id);

    void deleteByIds(@Param("ids") int []ids);
}

 

mybatis就是通过xml文件来简化我们的对数据库操作的大量代码。到底哪种简化程度只有自己去练习体会了。

 

 

                                                                                                                                                                                                                           

posted @ 2022-09-29 23:10  几人著眼到青衫  阅读(29)  评论(0)    收藏  举报