mybatis全局配置文件与映射文件详解

一、全局配置文件

1、概述

(1)SqlMapConfig.xml的配置内容和顺序如下(顺序不能乱):
Properties(属性)
Settings(全局参数设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境信息集合)
    environment(单个环境信息)
        transactionManager(事物)
        dataSource(数据源)
mappers(映射器)

2、全局配置—properties

(1)全局配置properties代码:

<!-- 加载Java配置文件或声明属性信息 -->
    <properties resource="jdbcInfo.properties">
        <!-- resource的加载顺序比property标签声明的属性更晚,因此会覆盖 -->
        <property name="jdbc.user" value="123"/>
    </properties>
<!-- 配置mybatis的环境信息,与spring整合是,该信息由spring来配置 -->
    <environments default="development">
        <environment id="development">
            <!-- 配置JDBC事务控制,由mybatis进行管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源,采用mybatis连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClass}"/>
                <property name="url" 
                value="${jdbc.jdbcUrl}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>

        </environment>

    </environments>

(2)数据库配置文件jdbcInfo.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/mybatis
jdbc.user=root
jdbc.password=root

(3)加载的顺序:

a、先加载properties中property标签声明的属性
b、再加载properties标签引入的java配置文件中的属性
c、parameterType的值会和properties的属性值发生冲突

3、全局配置—settings

这里写图片描述
这里写图片描述
这里写图片描述

4、全局配置—typeAliases

(1)typeAliases:对po类进行别名的定义

(2)全局配置代码:

<!-- 自定义别名 -->
    <typeAliases>
        <!-- 单个别名定义 -->
        <!-- type:需要被取代的全限定类名   alias:别名 
            <typeAlias type="com.san.model.User" alias="user"/>
        -->
        <!-- 批量别名定义(推荐) -->
        <!-- package:指定包名称来为该包下的PO类声明别名,默认的别名是类型(首字母大小写都可以) -->
        <package name="com.san.model"/>

    </typeAliases>

(3)映射文件代码:(次数映射文件中的resultType就不需要使用全限定类名,直接使用别名就可以了)

<select id="findUserById" parameterType="int" resultType="user">
        select * from user where id=#{id}
    </select>

5、全局配置—mappers

(1)使用相对于类路径的资源

<mapper resource=’’/>

(2)使用完全限定路径

<mapper url=’’/>

(3)使用mapper接口的全限定名
注意:此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下

<mapper class=’’/>

(4)注册指定包下的所有映射文件(推荐)
注意:此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下

<package name=’’/>

二、映射文件之输入映射

1、包装pojo类型

(1)问题描述:
综合查询时,可能会根据用户信息、商品信息、订单信息等作为条件进行查询,用户信息中的查询条件由;用户的名称和性别进行查询

(2)编写包装pojo

public class UserQueryvo {
    //用户信息
    private User user;

    private List<Integer> idList;

    public List<Integer> getIdList() {
        return idList;
    }

    public void setIdList(List<Integer> idList) {
        this.idList = idList;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

(3)编写映射文件:

<!-- 综合查询,查询用户列表 -->
    <!-- #{}中的参数名称要和包装pojo中的对象层级一致,并且属性名称要一致 -->
    <select id="findUserList" parameterType="com.san.model.UserQueryvo" resultType="user">
        select * from user
        <!-- where标签:默认去掉后面第一个and,如果没有参数,则把自己干掉 -->
        <where> 
            <!-- 引入sql片段 -->
            <include refid="whereClause"></include>
        </where>
    </select>

(4)mapper接口:

public List<User> findUserList(UserQueryvo vo);

(5)编写测试:

@Test
    //查询用户列表
    public void Test2() throws IOException{
        String resource="SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //sqlSession,它的内部含有一块数据区域,存在线程不安全,因此声明在方法内部
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //创建UserMappper对象
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        //执行查询语句
        UserQueryvo vo=new UserQueryvo();
        User user=new User();
        user.setUsername("李四");
        user.setSex("1");
        vo.setUser(user);
        List<User> list=userMapper.findUserList(vo);
        System.out.println(list);
        //关闭资源
        sqlSession.close();
    }

2、map类型

(1)映射文件:

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

(2)测试:

Public void testFindUserByHashmap()throws Exception{
        //获取session
        SqlSession session = sqlSessionFactory.openSession();
        //获限mapper接口实例
        UserMapper userMapper = session.getMapper(UserMapper.class);
        //构造查询条件Hashmap对象
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("id", 1);
        map.put("username", "管理员");

        //传递Hashmap对象查询用户列表
        List<User>list = userMapper.findUserByHashmap(map);
        //关闭session
        session.close();
    }

(3)异常测试:
传递的map中的key和sql中解析的key不一致
测试结果没有报错,只是通过key获取值为空

三、映射文件之输出映射

1、resultType

(1)使用要求:
a、使用resultType进行结果映射时,需要查询出的列名和映射的对象的属性名一致,才能映射成功。
b、如果查询的列名和对象的属性名全部不一致,那么映射的对象为空。
c、如果查询的列名和对象的属性名有一个一致,那么映射的对象不为空,但是只有映射正确那一个属性才有值。
d、如果查询的sql的列名有别名,那么这个别名就是和属性映射的列名。

(2)映射文件:

<!-- 综合查询,查询用户的总数 -->
    <select id="findUserCount" parameterType="com.san.model.UserQueryvo" resultType="int">
        select count(*) from user 
        <where>
            <include refid="whereClause"></include>
        </where>

    </select>

2、resultMap

(1)使用要求:
使用resultMap进行结果映射时,不需要查询的列名和映射的属性名必须一致。但是需要声明一个resultMap,来对列名和属性名进行映射。

(2)映射文件:

<!-- id标签:专门为查询结果中唯一列映射 -->
    <!-- result标签:映射查询结果中的普通列 -->
    <!-- type标签:返回类型 -->
    <resultMap type="user" id="UserResMap">
        <id column="id_" property="id"/>
        <result column="username_" property="username"/>
        <result column="sex_" property="sex"/>
    </resultMap>    
    <select id="findUserRstMap" parameterType="int" resultMap="UserResMap">
        select id id_,username username_,sex sex_ from user where id=#{id}  
    </select>

3、动态sql

(1)概述:
在mybatis中,它提供了一些动态sql标签,可以让程序员更快的进行mybatis的开发,这些动态sql可以通过sql的可重用性。

(2)常用的动态sql标签:
if标签、where标签、sql片段、foreach标签

(3)映射文件(总的映射文件):

<?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">

<!-- namespace:需要和mapper接口的全限定名一致 -->
<mapper namespace="com.san.mapper.UserMapper">

    <!-- 通过ID查询用户 -->
    <select id="findUserById" parameterType="int" resultType="user">
        select * from user where id=#{id}
    </select>

    <!-- 定义sql片段 -->
    <!-- sql片段内,可以定义sql语句中的任何内容 -->
    <!-- sql片段内,最好不要使用where和select关键字声明在内 -->
    <sql id="whereClause">
        <!-- if标签:对输入的参数进行判断 -->
        <!-- test标签:指定判断的表达式 -->
        <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>

        <!-- 判断集合 -->
        <!-- collection:表示pojo中集合属性的属性名称 -->
        <!-- item:为遍历出的结果声明一个变量名称 -->
        <!-- open:遍历开始时,需要拼接的字符串 -->
        <!-- close:遍历结束时,需要拼接的字符串 -->
        <!-- separator:遍历中间需要拼接的字符串 -->
        <if test="idList!=null">
            and id in
            <foreach collection="idList" item="id" open="(" close=")" separator=",">
                <!-- and id in (#{id},#{id},#{id}) -->
                #{id}
            </foreach>
        </if>
    </sql>

    <!-- 综合查询,查询用户列表 -->
    <!-- #{}中的参数名称要和包装pojo中的对象层级一致,并且属性名称要一致 -->
    <select id="findUserList" parameterType="com.san.model.UserQueryvo" resultType="user">
        select * from user
        <!-- where标签:默认去掉后面第一个and,如果没有参数,则把自己干掉 -->
        <where> 
            <!-- 引入sql片段 -->
            <include refid="whereClause"></include>
        </where>
    </select>

    <!-- 综合查询,查询用户的总数 -->
    <select id="findUserCount" parameterType="com.san.model.UserQueryvo" resultType="int">
        select count(*) from user 
        <where>
            <include refid="whereClause"></include>
        </where>

    </select>

    <!-- id标签:专门为查询结果中唯一列映射 -->
    <!-- result标签:映射查询结果中的普通列 -->
    <!-- type标签:返回类型 -->
    <resultMap type="user" id="UserResMap">
        <id column="id_" property="id"/>
        <result column="username_" property="username"/>
        <result column="sex_" property="sex"/>
    </resultMap>    
    <select id="findUserRstMap" parameterType="int" resultMap="UserResMap">
        select id id_,username username_,sex sex_ from user where id=#{id}  
    </select>
</mapper>
  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值