SSM框架详细讲解(一)Mybatis基础到深入(二)-mybatis配置文件的详细使用

Mybatis系列文章目录

一:Mybatis基础到深入(一)-mybatis的初步使用
二:Mybatis基础到深入(二)-mybatis配置文件的详细使用
三:Mybatis基础到深入(三)-mybatis的注解开发



一:SqlMapConfig.xml配置文件解释

从上文我们已经知道了Mybatis是什么,以及为什么需要它,最后讲了一点Mybatis常用的一些简单CRUD操作,本文会继续阐述我们实际使用mybatis所要知道的一些配置,在讲新东西之前,建议同学反复看上期的xml配置文件,争取滚瓜烂熟。

  • A.官方说明文档
    http://www.mybatis.org/mybatis-3/zh/configuration.html
  • B.SqlMapConfig.xml中配置的内容和顺序如下:
    • properties(属性)
    • settings(设置)
    • typeAliases(类型别名)
    • typeHandlers(类型处理器)
    • objectFactory(对象工厂)
    • plugins(插件)
    • environments(环境配置)
    • environment(环境变量)
    • transactionManager(事务管理器)
    • dataSource(数据源)
    • databaseIdProvider(数据库厂商标识)
    • mappers(映射器)
  • C.常用属性
    • properties
    • settings
    • typeAliases
    • mappers

后面会详细讲解每个属性的意思

二:Mybatis连接池

  • 在Mybatis中也有连接池技术,但是它采用的是自己的连接池技术。在 Mybatis 的SqlMapConfig.xml配置文件中,通过<dataSourcetype=“pooled”>来实现Mybatis 中连接池
    的配置。
  • Mybatis连接池分类
    在这里插入图片描述

可以看出 Mybatis 将它自己的数据源分为三类:

  • UNPOOLED 不使用连接池的数据源
  • POOLED 使用传统的javax.sql.DataSource规范中的连接池
  • JNDI 使用 JNDI 实现的数据源

在这三种数据源中,我们一般采用的是 POOLED 数据源(很多时候我们所说的数据源就是为了更好的管理数据库连接,也就是我们所说的连接池技术 。

三:XML配置信息如何写

在说配置信息之前,我先提前说一些东西,这关系我们到底要不要记住这些配置,以及实际项目开发过程中用不用的到
在这给同学们一个提醒,特别是刚接触mybatis,可能在其他学习途径看到,不用写这么多的xml配置信息,甚至会有专门的模板实际可以不用写,但是切记好高骛远,从最原始的,基本的开始学习,才会对最后的注解开发,和mybatis流程原理更加深刻。

还有同学不知道什么是xml,这类问题我会专门写一篇博客,详细讲解xml,要知道xml格式不仅可以当作配置文件,早在之前,风靡一时的xml还可以当作数据传输

3.1 SqlMapConfig.xml配置文件解释

3.1.1 environments标签

在这里插入图片描述

  • 在environments标签中,可以有多个environment子标签
  • transactionManager标签
    • 配置mybatis的事务管理器
    • JDBC:依赖于从数据源得到的连接来管理事务
    • MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个事务,而是让容器来管理事
      务的整个生命周期.
    • dataSource标签
      • 设置数据源
      • UNPOOLED:没有使用连接池,每次使用时新建一个连接,使用完后销毁连接
      • POOLED:使用连接池
  • 演示代码(建议讲此配置背熟)
<environments default="development1">
	<environment id="development1">
		<transactionManager type="JDBC">
		</transactionManager>
		<dataSource type="POOLED">
			<property name="driver" value="${driverClass}"/>
			<property name="url" value="${jdbcUrl}"/>
			<property name="username" value="${user}"/>
			<property name="password" value="${password}"/>
		</dataSource>
	</environment>
</environments>
3.1.2 properties标签
  • 配置mybatis属性值配置,可以配置数据源信息(网上有很多写法,只要意思,原理一样即可)
<properties resource="jdbc.properties">
	<property name="driverClass" value="com.mysql.jdbc.Driver"/>
	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/day27"/>
	<property name="user" value="root"/>
	<property name="password" value="root"/>
</properties>

resource表示则个配置从外部导入进来,可就是说,properties 可以在外部定义,然后导入我们配置的xml

3.1.3 typeAliases标签
  • 为 Java 类型设置一个别名:
    • 方式一: 给指定类设置别名
    • 方式二: 给指定包下的所有类设置别名
  • 方式一:
<typeAliases>  
    <typeAlias type="com.qzw.bean.User" alias="user"></typeAlias> 
 </typeAliases> 
  • 方式二
	<typeAliases>    
 		 <package name="com.qzw.bean"/> 
   </typeAliases> 
3.1.4 mappers标签
  • <mapper resource="" />:使用相对于类路径的资源
    如:<mapper resource="user.xml" />
  • <mapper class="" />:使用接口类路径
    如:<mapper class="com.qzw.dao.UserDao"/>
    注意:要求接口名称和映射文件名称相同,且放在同一个目录中。
  • <package name=""/>:注册指定包下的所有接口
    如:<package name="com.qzw.dao"/>.
    注意:要求接口名称和映射文件名称相同,且放在同一个目录中

3.2 映射(mapper)配置文件属性详解

sql查询的结果要映射到实例或者单个属性上,因此也叫映射文件,重要的是如何映射,xml方式为我们提供了resultType和resultMap分别对应不同情况进行结果映射,同时也给我提供parameterType的参数映射

3.2.1 parameterType属性
  • 给sql语句传入参数。将会传入这条语句的参数类的完全限定名或别名。这个属性是可选的。默 认值为未设置
  • paramType参数的类型
    • 简单数据类型 包含int,String等。只能传入一个参数。
    • 复杂数据类型 javaBean实体类, Map。可以传入多个参数
  • 案例演示
    a.根据id查询用户
    b.根据账户和密码查询用户
//映射文件  
<select id="selectUserByUsernameAndPassword" parameterType="user" resultType="user">    
  select * from tb_user where username = #{username} and password = #{password} 
</select> 

<select id="selectUserByUsernameAndPassword1" parameterType="map" resultType="user">   
    select * from tb_user where username = #{username} and password = #{password} 
</select> 

//测试代码  
@Test  public void selectUserByUsernameAndPassword() throws Exception {    
  ...... 
    User user = new User();   
    user.setUsername("wangwu");   
    user.setPassword("wangwu");   
    List<User> userList = userDao.selectUserByUsernameAndPassword(user);   
    ...... 
 } 
 
@Test  public void selectUserByUsernameAndPassword1() throws Exception {   
   ......   
   Map<String,String> map = new HashMap<>();   
   map.put("username","wangwu");   
   map.put("password","wangwu");   
   List<User> userList = userDao.selectUserByUsernameAndPassword1(map);   
   ......  
} 
 
3.2.2 映射配置文件之resultType属性
  • sql语句执行后返回结果类型。从这条语句中返回的期望类型的类的完全限定名或别名。
  • resultType参数的类型
    • 返回JavaBean类型
    • 返回List类型
    • 返回Map类型
  • 案例演示 :
    a.resultType为map,返回单条记录,key为属性名,值为属性值。
<select id="selectUserById" parameterType="int" resultType="map">     
 select * from tb_user where id = #{id} 
</select> 

结果为:
在这里插入图片描述

b.resultType为map,返回多条记录,key为任意一属性,值为对象类型,不过key需要通过 @MapKey(“hotelName”)指定对象中一个属性名为key

//映射文件 
<select id="selectUserList" resultType="map">   
   select * from tb_user 
</select> 

 //dao代码 
@MapKey("id") 
Map<Integer,Object> selectUserList() throws Exception; 

结果为:
在这里插入图片描述

3.2.3(重点,常用)映射配置文件-resultMap属性
  • resultType可以将查询结果映射为pojo,但需要pojo类的属性名和sql查询的字段名称一致方可映 射成功。
  • 如果sql查询字段名和pojo类的属性名不一致,可以通过resultMap将字段名和属性名作一个对 应关系.
  • resultMap可以实现将查询结果映射为复杂类型的pojo,比如实现一对一查询和一对多查询。
<!-- resultMap最终还是要将结果映射到pojo上,type就是指定映射到哪一个pojo -->
    <!-- id:设置ResultMap的id -->
    <resultMap type="order" id="orderResultMap">
        <!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
        <!-- property:主键在pojo中的属性名 -->
        <!-- column:主键在数据库中的列名 -->
        <id property="id" column="id" />

        <!-- 定义普通属性 -->
        <result property="userId" column="user_id" />
        <result property="number" column="number" />
        <result property="createtime" column="createtime" />
        <result property="note" column="note" />
    </resultMap>

3.2.4 映射配置文件-sql片段

在开发中,SQL的拼接很常见,有很多的sql具有重复性高的特点,这时最好把重复的sql抽取出 来,作为公用的sql片段。

  • 语法 :
    • 定义sql片段
<sql id="片段名">    
  sql语句  
</sql> 
  • 引用sql片段
<include refid="片段名"></include> 
3.2.5动态sql之if标签

mybatis 映射文件中,if标签判断字符串相等与否
语法:

<if test="OGNL表达式">   
   sql语句 
</if>

案例演示:
没有使用if标签

<select id="selectUserByUsernameAndPassword" parameterType="user"  resultType="user">   
   select * from tb_user where username = #{username} and password = # {password}  
</select> 
  • 以上案例存在一些问题:当username和password其中任意一个没有值,那么就找不到记 录 使用if标签
<select id="selectUserByUsernameAndPassword" parameterType="user"  resultType="user">    
  		select * from tb_user where 1 = 1
     <if test="username != null and username != ''">      
         and username = #{username}   
      </if> 
    <if test="password != null and password != ''">     
         and password = #{password}    
     </if>  
</select> 
3.2.6 动态sql之where标签

映射文件中的where标签可以省略’where 1 = 1’和’第一个if语句中的and或or’
语法:

<where>   
   sql语句  
</where> 

案例演示

<select id="selectUserByUsernameAndPassword" parameterType="user" resultType="user">   
   select * from tb_user   
      <where>    
            <if test="username != null and username != ''">         
                 username = #{username}    
            </if> 
           <if test="password != null and password != ''">       
                  and password = #{password}     
           </if>   
     </where> 
</select> 
3.2.6 动态sql之foreach标签

向sql传递数组或List,mybatis使用foreach解析.
语法 :

 <foreach collection="" open="" separator="" close="" item=""> 
    sql语句 
 </foreach>

collection:如果是数组值为array,如果是集合值为list
open:设置开头
separator:设置间隔
close:设置结尾
item:元素名

案例演示: 根据一组id值查询记录 使用数组 使用集合

//使用数组 
 <select id="selectUserListByIds1" parameterType="int[]" resultType="user">      select * from tb_user      
     <where> 
            <foreach collection="array" separator="," open="id in (" close=")"  item="id">           
                   #{id}           
            </foreach>        
 <!‐‐     <foreach collection="array" separator="or"  item="id">         
          id = #{id}            
            </foreach>       
  ‐‐>      
      </where> 
 </select> 
 
//使用集合 
 <select id="selectUserListByIds2" parameterType="list" resultType="user">    
   select * from tb_user   
    <where>      
        <foreach collection="list" separator="," open="id in (" close=")"  item="id">      
                #{id}       
        </foreach>   
    </where> 
</select> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值