mybatis简介

1、mybatis简介

mybatis是一款orm类型的数据持久化框架,将jdbc的手动注册驱动、建立连接、获取sql执行对象、释放连接等操作进行了自动化装配,只需要进行简单的配置就可以实现自动注册驱动、建立连接、释放连接等操作,开发人员只需要关注sql语句的编写就可以了,而不用过多的关注数据库连接问题。mybatis支持自定义 SQL、存储过程以及高级映射,可以通过sql映射文件实现sql语句的编写,支持动态sql,用条件判断进行查询可以实现sql复用。

2、mybatis优势
  • 通过参数映射方式,可以将参数灵活的配置在SQL语句中的配置文件中,避免在Java类中配置参数。
  • 通过输出映射机制,将结果集的检索自动映射成相应的Java对象,避免对结果集手工检索。
  • Mybatis可以通过Xml配置文件对数据库连接进行管理。
  • 实现了sql和java代码的分离,通过配置文件实现sql语句查询。
3、执行流程

在这里插入图片描述

4、获取mybatis对象
4.1 通过sqlSession获取dao层接口实现类对象
    //mybatis配置文件
    String resource = "mybatis.xml";
    //加载mybatis全局配置文件    
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(inputStream);
    // 非自动提交事务获取sqlSession对象,可携带参数boolean类型
    SqlSession sqlSession = factory.openSession(); 
    //获取dao层接口实现类对象
    StudentDao dao = sqlSession.getMapper(StudentDao.class);  
4.2 通过spring管理获取dao层接口实现类对象
  • spring配置文件中配置dao层映射文件扫描器,让spring管理dao层接口实现类对象
    <!--spring配置文件: 声明service,dao,工具类等对象-->
    <context:property-placeholder location="classpath:conf/jdbc.properties" />

    <!--声明数据源,连接数据库-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!--SqlSessionFactoryBean创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation"  value="classpath:conf/mybatis.xml" />
    </bean>
    
    <!--声明mybatis的扫描器,创建dao对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="com.bjpowernode.dao" />
    </bean>

    <!--声明service的注解@Service所在的包名位置-->
    <context:component-scan base-package="com.bjpowernode.service" />

  • 在java文件中通过注入方式获取dao层接口实现类对象
    //引用类型自动注入@Autowired, @Resource
    @Resource
    private StudentDao studentDao;
5、mybatis支持的别名
别名映射的类型
_bytebyte
_longlong
_shortshort
_intint
_integerint
_doubledouble
_floatfloat
_booleanboolean
stringString
byteByte
longLong
shortShort
intInteger
integerInteger
doubleDouble
floatFloat
booleanBoolean
dateDate
decimalBigDecimal
bigdecimalBigDecimal
mapMap/HashMap
5、动态sql语句

MyBatis的动态SQL是基于OGNL的表达式的。它对SQL语句进行灵活的操作,通过表达式判断来实现对SQL的灵活拼接、组装。

5.1 #{}${}的区别
  • insert into user (name) values (#{name}); ==> insert into user (name) values (?);
    #{}的作用主要是替换预编译语句(PrepareStatement)中的占位符?,可以防止sql注入。

  • insert into user (name) values ('${name}'); ==> insert into user (name) values ('tianshozhi');
    ${}符号的作用是直接进行字符串替换。

5.2 if元素

主要用于判断传入参数的有效性,可以动态的对多个字段判断,如果满足条件将会添加到查询语句之中,不满足则不填加。

    <select id="method" resultType="type">
        select * from table where name = 'demo'
            <if test="id != null and id != ''">
                and id = #{id}
            </if>
    </select>
5.3 choose-when-otherwise元素

类似于java的switch语句,choose相当于switch,when相当于case,otherwise相当于default。

    <select id="method" resultType="type">
        select * from table where name = 'demo'
        <choose>  
            <when test="id != null">  
                and id = #{id}
            </when>  
            <when test="email != null">  
                and email = #{mail }  
            </when>  
            <otherwise>  
                and age= "22"  
            </otherwise>  
        </choose>  
    </select>
5.4 where元素

where元素的作用就是在写入where元素的地方插入一个where,可以做一些智能处理:

  • 如果所有的条件都不满足那么MyBatis就会查出所有的记录
  • 如果输出后是and 开头的,MyBatis会把第一个and忽略
  • 在where元素中你不需要考虑空格的问题,MyBatis会智能的帮你加上
    <select id="method" resultType="type">
        select * from table
        <where>
            <if test="id != null and id != ''">
                and id = #{id}
            </if>
            <if test="mail != null and mail != ''">
                and mail = #{mail}
            </if>
        </where>
    </select>
5.5 trim元素

用于处理动态语句中的格式问题,可以去除动态生成sql语句中的多余符号,trim的属性有:
prefix:加上前缀
suffix:加上后缀
suffixOverrides:将尾部的指定内容覆盖掉
prefixOverrides:将首部的指定内容覆盖掉

    <insert id="method">
        insert into table
        <trim prefix="(" suffix=")" suffixoverrides=",">
            <if test="name != null">
                name,
            </if>
            <if test="id != null">
                id,
            </if>
        </trim>
        values
        <trim prefix="(" suffix=")" suffixoverrides=",">
            <if test="name != null">
                #{name},
            </if>
            <if test="id != null">
                #{id},
            </if>
        </trim>
    </insert>
5.6 set元素

set元素主要是用在更新操作的时候,它的功能和where类似,但是包含的内容不能为空,也就是必须有一个if标签内的值不为空。

    <update id="method">  
        update table  
        <set>  
            <if test="name != null">  
                name = #{name},  
            </if>  
            <if test="id != null">  
                id = #{id},  
            </if>
        </set>  
        where id = #{id}  
    </update>
5.7 foreach元素

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合,foreach元素的属性主要有:
item:表示集合中每一个元素进行迭代时的别名;
index:指定一个名字,用于表示在迭代过程中,每次迭代到的位置;
open:表示该语句以什么开始;
separator:表示在每次进行迭代之间以什么符号作为分隔符;
close:表示以什么结束;

    <delete id="method">
        delete from table where id in
        <foreach collection="array" item="ids" open="(" separator=","
            close=")">
            #{iditem}
        </foreach>
    </delete>
5.8 Case-when-then-else-end元素

类似于三原式表达式,可以通过条件判断得出需要输出的结果。

    <select id="method" resulttype="type">
		select
			name,
		    (case when time>=#{begin} then '1001' else '1002' end) time
		from
			table
		where
			id = #{id};
	</select>
  • 1
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值