2021-07-09

Mybatis

一、Mybatis概述

Mybatis是基于Java的持久层框架,它内部对jdbc进行了封装,使得开发者只需要关注Sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等复杂的过程;
mybatis通过xml或注解的方式将要执行的各种statement配置起来,并通过Java对象和statement中的SQL的动态参数进行映射生成最终执行的sql语句,然后又mybatis框架执行sql并将结果映射为java对象并返回;
采用ORM思想解决了实体和数据库映射的问题,对jdbc进行了封装,屏蔽了jdbc api底层访问细节,使得我们不用与jdbc api打交道,就可以完成对数据库的持久操作。
ORM解释: (object relational mapping) 兑现关系映射
理解:把数据库的表和实体类及实体类的属性一一对应起来,使得我们操作实体类即可实现对数据库的操作

二、使用

1.前期准备

1.在 maven 的 pom.xml 中配置 mybatis ,mysql,mybatis,lo4j2,以及junit的开发包:

	 <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!--log4j日志文件依赖包-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.14.1</version>
        </dependency>

        <!-- junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

2.创建数据库:
在这里插入图片描述

3.配置 MyBatis 的核心配置文件,在 resources 目录下创建 mybatis.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>
<!--在实际的工程之中,类的全限定名称很长,当我们需要大量使用的时候,这非常不方便的,mybatis提供了typeAlias别名标签供我们别名和自定义别名-->
<!--    <typeAliases>-->
<!--        <typeAlias type="com.zx.model.Student" alias="student"></typeAlias>-->
<!--    </typeAliases>-->
    <!--
    environments:配置mybatis开发环境,可以配置多个具体环境,每个环境对应一个数据库
    default:指定默认使用的开发环境,该属性的值为具体环境(environment)的id属性值
    -->
    <environments default="development">
        <!--
        environment:配置一个具体的mybatis环境
        id:为当前环境配置的一个唯一的标识,可以通过该标识来引用当前环境
        -->
        <environment id="development">
            <!--
            transactionManager:指定当前配置所使用的事务管理器
            type="JDBC":指定当前所使用的事务管理的方式,JDBC表示使用数据资源管理事务
            -->
            <transactionManager type="JDBC"/>
            <!--
            dataSource:配置数据源
                type:POOLED:指定使用数据库连接池的方式配置数据源
                    UNPOOLED:不使用数据库连接池
                    JNDI:使用外部数据源
            -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定映射配置文件的位置,映射配置文件指的是每一个mapper独立的配置文件-->
    <mappers>
    	    <mapper resource="mapper/studentMapper.xml"/>
	        <mapper resource="mapper/OrderMapper.xml"/>
    </mappers>
</configuration>

4.创建实体类Student并自动生成get,set,toString方法
5.创建StudentMapper接口(mapper就是dao,在mybatis中习惯使用mapper)

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zx.mapper.StudentMapper">
<!--
 SQL映射文件,该文件用于:
     1.配置对象模型和关系模型之间映射(表中的那个字段与对象中的那个属性对应)
     2.映射SQL语句,在该文件中编写SQL语句
-->
<!--将对象模型和关系模型映射匹配,如果对象中的属性和表中的列名及类型一致mybatis会自动映射,无需配置-->
<!--
        select:查询语句
        id:唯一标识
        resultType:指定查询结果要封装的对象所属的类
        标签体为SQL语句
    -->
    </mapper>

2.单表的增删改查操作

1.添加学生
<!--保存用户-->
    <insert id="saveStudent" parameterType="student">
    <!--配置插入操作后,获取插入数据得id-->
        <selectKey keyProperty="stu_id" keyColumn="stu_id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into Student(stu_name,stu_sex,stu_birth,stu_major,stu_address)
        values(#{stu_name},#{stu_sex},#{stu_age},#{stu_major},#{stu_address})
    </insert>
2.删除学生

根据一个id删除一个学生

delete id="deleteStudent" parameterType="Integer">
        delete from student where stu_id=#{stu_id}
    </delete>

多个id删除多个学生

    <delete id="delStudent">
        <if test="stu_ids!=null and stu_ids.length!=0">
           delete from student
           <where>
               stu_id in
             <foreach collection="stu_ids" open="(" close=")" separator="," item="stu_id">
              #{stu_id}
             </foreach>
           </where>
        </if>
    </delete>
3.修改学生信息
<!--检单的更新学生-->
    <update id="updateStudent" parameterType="student">
        update student set
        stu_name=#{stu_name},stu_sex=#{stu_sex},stu_age=#{stu_age},stu_major=#{stu_major},stu_address=#{stu_address}
        where stu_id=#{stu_id}
    </update>

动态sql语句,set标签的使用

    <update id="updateStudent">
        update student
        <set>
            <if test="stu_name != null and stu_name!=''">
                stu_name=#{stu_name},
            </if>
            <if test="stu_sex != null and stu_sex!=''">
                 stu_sex=#{stu_sex},
            </if>
            <if test="stu_age!=null">
                stu_age=#{stu_age}
            </if>
        </set>
        <where>
            stu_id=#{stu_id}
        </where>
    </update>

动态sql语句trim的使用

    <update id="updateStudent1">
        update student
        <trim prefix="set" suffixOverrides=",">
            <if test="stu_name != null and stu_name!=''">
                stu_name=#{stu_name},
            </if>
            <if test="stu_sex != null and stu_sex!=''">
                stu_sex=#{stu_sex},
            </if>
            <if test="stu_age!=null">
                stu_age=#{stu_age}
            </if>
        </trim>
        <trim prefix="where">
            stu_id=#{stu_id}
        </trim>
    </update>

4.查找学生
	<!--根据id查询一个学生-->
   	<select id="findById" parameterType="Integer" resultType="student">
        select * from student where stu_id=#{stu_id}
    </select>
    <!--根据姓名模糊查询-->
    <select id="findByName" parameterType="String" resultType="student">
        select * from student where stu_name like concat('%',#{stu_name},'%') 
    </select>
  <!--多条件查询-->
    <select id="queryStudents" resultType="com.zx.model.Student">
        select * from student
        <where>
        <if test="stu_name != null and stu_name!=''">
            stu_name like concat('%',#{stu_name},'%')
        </if>
        <if test="stu_sex != null and stu_sex!=''">
            and stu_sex=#{stu_sex}
        </if>
        <if test="stu_start_age!=null">
            and stu_age &gt;= #{stu_start_age}
        </if>
        <if test="stu_end_age !=null">
            and stu_age &lt;= #{stu_end_age}
        </if>
        </where>
    </select>
  <!--查询某个年龄段区间的学生-->
    <select id="queryStudentByAge" resultType="com.zx.model.Student">
        select * from student
        <where>
            <choose>
                <when test="stu_start_age!=null">
                    stu_age &gt;= #{stu_start_age}
                </when>
                <when test="stu_end_age!=null">
                   stu_age &lt;= #{stu_end_age}
                </when>
                <otherwise>
                    stu_age between 19 and 30
                </otherwise>
            </choose>
        </where>
    </select>

3多表连接查询

1创建数据库

商品表在这里插入图片描述

订单表

订单明细表在这里插入图片描述
创建订单的实体对象,以及mapper接口

2一对多的查询

一个用户可以有有多个订单

studentMapper.xml
<!--关联映射-->
    <resultMap id="studentOrderMap" type="com.zx.model.Student" autoMapping="true">
    <!--配置一对多关联的一方 collection
    property:对象中的属性名
    column:关系模型中的外键
    ofType:指定关联对象
    select:查询关联对象所使用的SQL(此处的sql配置为SQL映射)
    fetchType:设置使用懒加载机制
    -->
    <collection property="ordersList" column="stu_id"
                ofType="com.zx.model.Orders"
                select="com.zx.mapper.OrderMapper.queryOrderByStudentId"
                fetchType="lazy">
    </collection>
    </resultMap>
    <select id="queryStudentByStudentId" resultMap="studentOrderMap">
        select * from student where stu_id=#{stu_id}
    </select>



orderMapper.xml
  <select id="queryOrderByStudentId" resultType="com.zx.model.Orders">
        select * from orders where stu_id=#{stu_id}
    </select>
orderMapper.xml
    <resultMap id="orderStudentMap" type="com.zx.model.Orders">
        <!--配置一对多的多方
         property:对象中的属性名
        column:关系模型中的外键
         select:查询关联对象所使用的SQL(此处的sql配置为SQL映射)
         fetchType:设置使用懒加载机制
         -->
        <association property="student"
                     column="stu_id"
                     select="com.zx.mapper.StudentMapper.queryStudentByStudentId"
                    fetchType="lazy">
        </association>
    </resultMap>

    <select id="queryOrderByOrderId" resultMap="orderStudentMap">
        select * from orders where order_id=#{order_id}
    </select>

studentMapper.xml
    <select id="queryStudentByStudentId" resultType="com.zx.model.Student">
        select * from student where stu_id=#{stu_id}
    </select>

总结

对自己学习的Mybatis进行了简单的总结,多表连接的多对多映射,以及注解的方式稍后补充。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小粥呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值