mybatis----基础

2018-08-01  本文已影响0人  全满

基础知识

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>

对原生态jdbc程序中问题总结

java环境:jdk

使用jdbc查询mysql数据库中用户表的记录

mybatis是什么

mybatis是一个持久层框架,是apache下的顶级项目。
mybatis是让程序员将主要精力放在sql上,通过mybatis提供的映射方式,自由灵活的生成(半自动化,大部分需要程序员编写sql)满足需要的sql语句
mybatis可以将向preparedStatement中的输入参数自动进行输入映射,将查询结果集灵活映射成java对象(输出映射)

mybatis框架

SqlMapConfig.xml     是mybatis的全局配置文件,配置了数据源、事务等mybatis运行环境(第三方软件进行配置)

mybatis自己还需要配置映射文件(mapper.xml、mapper.xml、mapper.xml……【映射文件】)也就是配置sql语句

SqlSessionFactory(会话工厂),根据配置文件创建工厂
作用:创建SqlSession
SqlSession(会话),是一个接口,面向用户(程序员)的接口
作用:操作数据库(发出增、删、改、查)
Executor(执行器),也是一个接口(基本执行器、缓存执行器)
作用:操作数据库(发出增、删、改、查)
mapped statement(底层封装对象)
作用:对操作数据库存储封装,包括sql语句,输入参数、输出结果类型

入门程序

# Global logging configuration
#在开发环境下日志级别要设置成DEBUG,生成环境设置成info或ERROR
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
User.xml(原始mybatis命名),mapper代理开发映射文件叫xxxMapper.xml,比如:UserMapper.xml
在映射文件中配置sql语句
image.png
image.png

#{}与${}

parameterType、resuletType

parameterType : 指定输入参数的类型
resuletType : 指定输出参数的类型

自增主键返回

mysql自增主键,执行insert提交之前自动生成一个自增主键。
通过mysql函数获取到刚插入记录的自增主键:
LAST_INSERT_ID()
是在insert之后调用此函数,需要修改UserInsert的定义

<insert id=“insertUser” parameter="cn.persist.entily.User">
    <!-- 
      将插入数据的主键返回,返回到user对象中
      SELECT LAST_INSERT_ID():得到刚insert进去的记录的主键的值,只适用于自增主键
      KeyProperty:将查询到的主键值parameterType指定的对象的哪个属性
      order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
      resultType:指定SELECT LAST_INSERT_ID()的结果类型
     -->
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Inteager">
          SELECT LAST_INSERT_ID()
    </selectKey>
    <!--
          username,password,address是数据表中的对应的字段名称
          #{username},#{password},#{address}是实体类中对应的属性名
    -->
    INSERT into user(username,password,address) value(#{username},#{password},#{address})
</insert>

非自增主键返回(使用uuid)

使用mysql的uuid()函数生成主键,需要修改表中id字段类型为string,长度设置成35位
执行思路:
先通过uuid()查询到主键,将主键输入到sql语句中
执行uuid()语句顺序相对于insert语句之前执行

<insert id=“insertUser” parameter="cn.persist.entily.User">
    <!-- 
      使用mysql的uuid()生成主键
      执行过程:
      首先通过uuid()得到主键,将主键设置到user对象的id属性中
      其次在insert执行时,从user对象中取出id属性值
     -->
    <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
          SELECT uuid()
    </selectKey>
    <!--
          id,username,password,address是数据表中的对应的字段名称
          #{id},#{username},#{password},#{address}是实体类中对应的属性名
    -->
    INSERT into user(id,username,password,address) value(#{id},#{username},#{password},#{address})
</insert>

mybatis开发dao的方法

原始dao开发方法(程序员需要写dao接口和dao实现类)

程序员需要写dao接口和dao实现类。
需要向dao实现类中注入sqlSessionFactory(会话工厂),在方法体内通过工厂(sqlSessionFactory)创建sqlSession

1.dao的接口实现类方法中存在大量模板方法,设想能否将这些代码提取出来
2.调用sqlSession方法时将statement的id硬编码了
3.调用sqlSession方法时传入的变量,由于sqlSession方法使用泛型,即使变量类型传入错误,在编译阶段也不报错,只有在运行时报错,不利于程序开发

mapper代理方法(程序员只需要mapper接口(相当于dao接口))

1.程序员只需要mapper接口(相当于dao接口),需要遵循一些开发规范,mybatis可以自动生成mapper接口实现类的代理对象
2.程序员还需要编写mapper.xml映射文件

总结

以上开发规范主要是对下边的代码进行统一的生成:


image.png

SqlMapConfig.xml

需求:
将数据库连接的参数单独配置在db.properties中,只需要在sqlMapConfig.xml中加载db.properties的属性值
SqlMapConfig.xml中就不需要对数据库连接参数硬编码
将数据库连接参数只配置在db.properties中,原因:方便对参数进行统一的管理,其他xml可以引用该db.properties

db.properties的文件

image.png

sqlMapConfig.xml加载属性名称

image.png
image.png
建议:
不要在properties元素体内添加任何属性值,只将属性值定义在properties文件中

mybatis框架在运行时可以调整一些运行参数
比如:开启二级缓存、开启延时加载……
全局参数将会影响mybatis的运行行为

在dao.xml中的返回值类型填实体类的名称,首字母大写小写都可以

在mybatis中通过typeHandles完成jdbc类型和java类型的转换

动态sql

mybatis核心就是对sql语句进行灵活的操作,通过表达式进行判断,对sql进行灵活拼接、组装

用户信息总和查询列表和用户信息查询列表总数这两个statement的定义使用动态sql
对查询条件进行判断,如果输入参数不为空才能进行查询条件拼接;例如:

   <select id="findUserById" parameterType="User" resultType="user">
        select * from user
        <!--where 可以自动去掉条件中的第一个and-->
        <where>
            <if test="userCustom!=null">
                <if test="userCustom.usermame!=null and userCustom!=''">
                    and user.username = #{userCustom.username}
                </if>
                <if test="userCustom.sex != null and userCustom.sex != ''">
                    and user.sex = #{userCustom.sex}
                </if>
            </if>
        </where>
    </select>

sql片段

将上边实现的动态sql判断代码块抽取出来,组成一个sql片段。其他的statement中就可以引用sql片段

    <!--定义sql片段
    id:sql片段的唯一标识
    经验:是基于表单来定义sql片段可重用性高
    在sql片段中不要包括where
    -->
    <sql id="query_user_where">
        <if test="userCustom!=null">
            <if test="userCustom.usermame!=null and userCustom!=''">
                and user.username = #{userCustom.username}
            </if>
            <if test="userCustom.sex != null and userCustom.sex != ''">
                and user.sex = #{userCustom.sex}
            </if>
        </if>
    </sql>

应用sql片段

<select id="findUserById" parameterType="User" resultType="user">
        select * from user
        <!--where 可以自动去掉条件中的第一个and-->
        <where>
            /*应用sql片段*/
            <include refid="query_user_where" />
            /*在这里还会引用其他的sql片段*/
        </where>
    </select>

foreach

向sql传递数组或list,mybatis使用foreach解析

在用户查询列表和查询总数的statement中增加多个id输入查询
sql语句如下:
select * from user where id=1 or id=10 or id=16select * from user where id in(1,10,16)

在查询条件中,查询条件定义成一个sql片段,需要修改sql片段

<!--定义sql片段
   id:sql片段的唯一标识
   经验:是基于表单来定义sql片段可重用性高
   在sql片段中不要包括where
   -->
    <sql id="query_user_where">
        <if test="ids!=null">
            <!--使用foreach遍历传入ids
            collection:指定输入对象中集合属性
            item:每次遍历生成的对象
            open:开始遍历时拼接的串
            close:结束遍历时拼接的串
            separator:遍历的两个对象中需要拼接的串
            -->
            <foreach collection="ids" item="user_id" open="and (" close=")" separator="or">
                /*每次遍历需要拼接的串*/
                id=#{user_id}
            </foreach>
        </if>
    </sql>

select * from user where id in(1,10,16)的foreach查询方法

image.png
上一篇 下一篇

猜你喜欢

热点阅读