Mybatis持久层框架&MBG&Example类详解

Mybatis

1. 概念

1.1 什么是Mybatis

是一个持久层框架;

所谓持久层,也就是数据访问层。又称为DAL层,有时候也称为是持久层,其功能主要是负责数据库的访问。

我的理解就是Mybaits就是优化Dao层的一个框架。

1.2 优点

2. Mybatis小程序

2.1编写步骤

0.导入jar包
1.编写mybatis核心配置文件
	1.1配置jdbc
	1.2配置mapper????
    <mappers>
            <mapper resource="com/gao/dao/userMapper.xml"/>
        </mappers>
2.编写mybatis工具类
	这个应该只是起到辅助功能,把获取SqlSession连接的操作封装起来
3.编写Maper接口
    public interface UserMapper {
        List<User> selectUser();
    }
4.编写mapper配置文件??
    <mapper namespace="com.gao.dao.UserMapper">
        <select id="selectUser" resultType="com.gao.User">
               select * from user
        </select>
    </mapper>

2.2操作解析

1.namespace

<mapper namespace="com.gao.dao.UserMapper">
  • namespace中的路径为对应的接口完整路径;

2.select

 <select id="selectUser" resultType="com.gao.User">
               select * from user
        </select>
<select id="selectUserByPage" parameterType="map" resultType="com.gao.User">
        select * from user limit #{startIndex} ,#{pageSize}
    </select>
???parameterType???是干啥的
  • SQL语句返回值类型:

    https://blog.csdn.net/codejas/article/details/79520246

  • 传入SQL语句的参数类型 。

    ==万能的map=

    使用步骤:

    1.
    <select id="selectByNameAndAge" parameterType="map" resultType="com.gao.User">
    2.
    User selectByNameAndAge(Map<String,Object> map);
    3.
    UserMapper mapper = session.getMapper(UserMapper.class);
    Map<String,Object> map=new HashMap<String, Object>();
    map.put("age",12);
    
  • 命名空间中唯一的标识符

  • 接口中的方法名与映射文件中的SQL语句ID 一一对应

2.3配置文件解析

<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/mybatis?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/gao/dao/userMapper.xml"/>
    </mappers>
</configuration>

3.Mybatis生命周期及作用域

3.1生命周期

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FeQrVHaZ-1628558506968)(C:\Users\CoolGuy\AppData\Roaming\Typora\typora-user-images\image-20210723144618160.png)]

3.2作用域

4.ResultMap、分页、日志

4.1ResultMap

难 搞 嗷

4.2分页

实现方法

1.数据库分页;2.Java代码分页;3.插件实现

MyBatis 分页插件 PageHelper

4.3注解开发

我的理解

就是把UserMaper中的配置信息(Sql语句)放到注解上实现。

5. 1vN,Nv1查询,动态Sql

小记:

您瞪着大眼珠子瞅了1小时,没看懂的还是没看懂;用10分钟把看懂的部分搭建后,自然就懂了~~。

5.1 1vN

关键代码

<association property="teacher"  column="tid" javaType="Teacher" select="getTeacher"/>

我的分析

把数据库中查询到的对象,用映射的方式整合起来,即association。

按结果嵌套

<resultMap id="StudentTeacher2" type="Student">
   <id property="id" column="sid"/>
   <result property="name" column="sname"/>
   <!--关联对象property 关联对象在Student实体类中的属性-->
   <association property="teacher" javaType="Teacher">
       <result property="name" column="tname"/>
   </association>
</resultMap>

6. 缓存

7.MBG

MyBatis Generator (MBG) is a code generator for MyBatis MyBatis and iBATIS. It will generate code for all versions of MyBatis, and versions of iBATIS after version 2.2.0. It will introspect a database table (or many tables) and will generate artifacts that can be used to access the table(s). This lessens the initial nuisance of setting up objects and configuration files to interact with database tables. MBG seeks to make a major impact on the large percentage of database operations that are simple CRUD (Create, Retrieve, Update, Delete). You will still need to hand code SQL and objects for join queries, or stored procedures.

​ MyBatis Generator的作用就是根据数据库中的表结构,帮我们自动生成和表结构相同的实体类mapper接口包含基本增删改查语句的XML文件

7.1使用步骤

  1. 导入依赖jar包,并编写mbg.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <context id="DB2Tables" targetRuntime="MyBatis3">

        <!-- 去掉生成的结构中多余的注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 配置数据库连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 指定javaBean生成的位置 -->
        <javaModelGenerator targetPackage="com.gao.bean"
                            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--指定mapper.xml文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 指定mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.gao.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 指定每个表对应的java类型 -->
        <table tableName="tbl_stu" domainObjectName="Student"></table>
        <table tableName="tbl_dept" domainObjectName="Department"></table>
    </context>
</generatorConfiguration>
==============
生成的对象有:
1.实体类、实体名+Example类
2.实体类+Mapper接口
3.实体类+Mapper.xml文件
  1. MVC整合Mybatis框架
<!-- 和MyBatis整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="pooledDataSource"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

7.2在SSM中使用MBG的流程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-onRjuPhM-1628558506971)(file:///G:\QQDownload\2152843846\Image\Group2\XR\3Q\XR3QNCU7853}P@6@%1`PP%S.jpg)]

7.3***Example类解析

  1. 分析

​ 我理解的Example类的作用是添加条件,相当where后面的部分。

    protected String orderByClause;
 		//distinct字段用于指定DISTINCT查询。
    protected boolean distinct;
         //orderByClause字段用于指定ORDER BY条件,这个条件没有构造方法,直接通过传递字符串值指定。
    protected List<Criteria> oredCriteria;
         //oredCriteria字段用于自定义查询条件。

生成的Example类会有以上3个成员变量。

  1. 方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YIePvOTe-1628558506973)(C:\Users\CoolGuy\AppData\Roaming\Typora\typora-user-images\image-20210810091516530.png)]

  1. 举栗

在StuService中:

studentExample.setOrderByClause("stu_id asc");
        return studentMapper.selectByExampleWithDept(studentExample);

在StuExample中:

public void setOrderByClause(String orderByClause) {
    this.orderByClause = orderByClause;
}
======
    该方法将传入的参数赋值给orderByClause,让StuMapper.xml文件可以调用。

在StuMapper.xml中:

  <if test="orderByClause != null">
    order by ${orderByClause}
  </if>
</select>

中:

public void setOrderByClause(String orderByClause) {
    this.orderByClause = orderByClause;
}
======
    该方法将传入的参数赋值给orderByClause,让StuMapper.xml文件可以调用。

在StuMapper.xml中:

  <if test="orderByClause != null">
    order by ${orderByClause}
  </if>
</select>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

高冷小伙

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

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

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

打赏作者

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

抵扣说明:

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

余额充值