mybatis框架——配置文件详解

一、全局配置文件

1、概览

全局配置文件(SqlMapConfig.xml)的配置内容和顺序如下(顺序不能乱):

  • Properties(属性)
  • Settings(全局参数设置)
  • typeAliases(类型别名)
  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
  • environments(环境信息集合)
  • environment(单个环境信息)
  • transactionManager(事物)
  • dataSource(数据源)
  • mappers(映射器)

2、常用配置

1.Properties

        即配置加载properties文件,首先创建db.properties:

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
db.username=root
db.password=root

那么配置文件:

<configuration>
    <!-- 加载java的配置文件或者声明属性信息 -->
    <properties resource="db.properties">
    </properties>
​
    <!-- 配置mybatis的环境信息,与spring整合,该信息由spring来管理 -->
    <environments default="development">
        <environment id="development">
            <!-- 配置JDBC事务控制,由mybatis进行管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源,采用mybatis连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
</configuration>

注意,如果:

<properties resource="db.properties">
    <property name="db.username" value="123" />
</properties>

还是会加载properties文件中的username,因为先加载配置内容,再加载properties文件,后者会覆盖前者。

parameterType的值会和properties的属性值发生冲突。

2.typeAliases

       对po类进行别名的定义,其中mybatis支持的别名有:

               别名                  原名
_byte byte
_long long 
_short short 
_int int 
_integer int 
_double double 
_float float 
_boolean boolean 
string  String 
byte Byte 
long Long 
short Short 
int Integer 
integer Integer 
double Double 
boolean Boolean 
float Float 
date Date 
decimal BigDecimal 
bigdecimal BigDecimal 

   

当然也可以自定义别名:

<!-- 自定义别名 -->
<typeAliases>
    <!-- 单个别名定义 -->
    <!-- <typeAlias type="com.itheima.mybatis.po.User" alias="user"/> -->
​
    <!-- 批量别名定义(推荐) -->
    <!-- package:指定包名称来为该包下的po类声明别名,默认的别名就是类名(首字母大小写都可) -->
    <package name="com.itheima.mybatis.po" />
</typeAliases>

那么在映射文件中就可以使用user来替代其全限定名。

3.mappers

在引入映射文件时有如下几种格式:

  • <mapper resource=’’/>:使用相对于类路径的资源【如:<mapper resource="sqlmap/User.xml" />】
  • <mapper url=’’/>:使用完全限定路径【如:<mapper url="file:///D:\workspace_spingmvc\mybatis_01\config\sqlmap\User.xml" />】
  • <mapper class=’’/>:使用mapper接口的全限定名【如:<mapper class="cn.itcast.mybatis.mapper.UserMapper"/>】
  • <package name=’’/>(推荐):注册指定包下的所有映射文件【如:<package name="cn.itcast.mybatis.mapper"/>】

注意:后两种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下。

二、映射文件

1、输入映射

1.简单类型

参考《mybatis框架——基本应用》中根据用户ID查询用户信息的映射文件

2.Pojo类型

参考入门中添加用户的映射文件

3.包装pojo类型

      在综合查询时,可能会根据用户信息、商品信息、订单信息等作为条件进行查询,用户信息中的查询条件由:用户的名称和性别进行查询。需要先创建pojo的包装类:

public class UserQueryVO {
    private User user;//用户信息
        //setget
}

然后在映射文件中:

<!-- 综合查询,查询用户列表 -->
<select id="findUserList" parameterType="com.itheima.mybatis.po.UserQueryVO" resultType="user">
        SELECT * FROM user WHERE
        username LIKE '%${user.username}%'
        AND sex=#{user.sex}
</select>

在Mapper接口中:

public List<User> findUserList(UserQueryVO vo);

4.Map类型

       同传递POJO对象一样,map的key相当于pojo的属性。映射文件如下:

<!-- 传递hashmap综合查询用户信息 -->
<select id="findUserByHashmap" parameterType="hashmap" resultType="user">
  select * from user where id=#{id} and username like '%${username}%'
</select>

2、输出映射

1.resultType

      使用resultType进行结果映射时,需要查询出的列名和映射的对象的属性名一致,才能映射成功。如果查询的列名和对象的属性名全部不一致,那么映射的对象为空;如果查询的列名和对象的属性名有一个一致,那么映射的对象不为空,但是只有映射正确那一个属性才有值。

说明:如果查询的sql的列名有别名,那么这个别名就是和属性映射的列名。

1.简单类型

       注意,对简单类型的结果映射也是有要求的,查询的列必须是一列,才能映射为简单类型。综合查询时,需要根据综合查询的添加查询用户的总数,首先映射文件:

<select id="findUserCount" parameterType="com.itheima.mybatis.po.UserQueryVO"  resultType="int">
    SELECT count(*) FROM user WHERE
               username LIKE '%${user.username}%'
               AND sex=#{user.sex}
</select>

在Mapper接口中:

//综合查询用户总数
public int findUserCount(UserQueryVO vo);

2.Pojo对象和pojo列表

参考入门程序之根据用户ID查询用户信息和根据用户名称模糊查询用户列表

2.resultMap

      使用resultMap进行结果映射时,不需要查询的列名和映射的属性名必须一致。但是需要声明一个resultMap,来对列名和属性名进行映射。如,对以下sql查询的结果集进行对象映射:

Select id id_,username username_,sex sex_ from user where id = 1;

在映射文件中:

<resultMap type="user" id="UserRstMap">
    <id column="id_" property="id" />
    <result column="username_" property="username" />
    <result column="sex_" property="sex" />
</resultMap>
​
<select id="findUserRstMap" parameterType="int" resultMap="UserRstMap">
    Select id id_,username username_,sex sex_ from user where id = #{id}
</select>

说明:

id标签:专门为查询结果中唯一列映射

result标签:映射查询结果中的普通列

在Mapper接口中:

public User findUserRstMap(int id);

3、动态sql

       在mybatis中,它提供了一些动态sql标签,可以让程序员更快的进行mybatis的开发,这些动态sql可以通过sql的可重用性。常用的动态sql标签:if标签、where标签、sql片段、foreach标签。

1.If标签/where标签

      在综合查询时,查询条件由用户来输入,用户名称可以为空,需要满足这种情况下的sql编写:

<!-- 综合查询,查询用户列表 -->
<select id="findUserList" parameterType="com.itheima.mybatis.po.UserQueryVO"  resultType="user">
    SELECT * FROM user
    <where>
        <if test="user != null">
            <if test="user.username != null and user.username != ''">
                AND username LIKE '%${user.username}%'
            </if>
            <if test="user.sex != null and user.sex != ''">
                AND sex = #{user.sex}
            </if>
        </if>   
    </where>
</select>

解释:

  • where标签:默认去掉后面第一个AND,如果没有参数,则把自己干掉(还有一个set标签,去掉最后面的','号)
  • if标签:可以对输入的参数进行判断
  • test:指定判断表达式

除了可以将代码直接写在该处,还可以写在sql块中,然后调用:

<sql id="whereClause">
    <if test="user != null">
        <if test="user.username != null and user.username != ''">
            AND username LIKE '%${user.username}%'
        </if>
        <if test="user.sex != null and user.sex != ''">
            AND sex = #{user.sex}
        </if>
    </if>
</sql>
​
<select id="findUserList" parameterType="com.itheima.mybatis.po.UserQueryVO"
    resultType="user">
    SELECT * FROM user
    <where>
        <!-- 引入sql片段 -->
        <include refid="whereClause" />
    </where>
</select>

注意:sql片段内,最好不用将where和select关键字声明在内。

2.Foreach标签

       可以循环传入参数值。综合查询时,会根据用户ID集合进行查询(批量删除),如下面SQL:

SELECT * FROM USER WHERE id IN (1,2,10)

首先修改包装pojo:

public class UserQueryVO {
    private User user;//用户信息
    private List<Integer> idList;//ID集合
}

然后在sql片段中需要拼凑出:AND id IN (#{id},#{id},#{id}) 

<sql id="whereClause">
    <if test="idList != null">
        AND id IN
        <foreach collection="idList" item="id" open="(" close=")"
            separator=",">
            #{id}
        </foreach>
    </if>
</sql>

解释:

  • collection:表示pojo中集合属性的属性名称
  • item:为遍历出的结果声明一个变量名称
  • open:遍历开始时,需要拼接的字符串
  • close:遍历结束时,需要拼接的字符串
  • separator:遍历中间需要拼接的连接符

如果直接传递的是List集合,则:

<select id="findUsersByIdList" parameterType="java.util.List" resultType="user">
    SELECT * FROM USER
    <where>
        <if test="list  != null and list.size > 0">
            <foreach collection="list" item="id" open="AND id IN (" close=")" separator=",">
                #{id}
            </foreach>
        </if>
    </where>
</select>

猜你喜欢

转载自blog.csdn.net/qq_22172133/article/details/81275995