为什么80%的码农都做不了架构师?>>>   

Mybatis配置

在ApplicationContext上加上如下配置:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mapperLocations" value="classpath*:mapper/*.xml" /><property name="configLocation" value="classpath:mybatis-config.xml"/></bean><bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg index="0" ref="sqlSessionFactory" /></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="sbeat.dao" />
</bean>

然后在mybatis-config.xml中做进一步的配置。

<configuration><typeAliases><package name="sbeat.model" /></typeAliases></configuration>

Mybatis 分页

Mybatis不支持分页,所以我采用了PageHelper这个插件,首先在你的Mybatis配置文件里加上一下配置


<plugins><!-- com.github.pagehelper为PageHelper类所在包名 --><plugin interceptor="com.github.pagehelper.PageHelper"><property name="dialect" value="mysql" /><!-- 该参数默认为false --><!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 --><!-- 和startPage中的pageNum效果一样 --><!-- <property name="offsetAsPageNum" value="false" /> --><!-- 该参数默认为false --><!-- 设置为true时,使用RowBounds分页会进行count查询 --><!-- <property name="rowBoundsWithCount" value="false" /> --><!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 --><!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型) --><property name="pageSizeZero" value="true" /><!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 --><!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 --><!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 --><property name="reasonable" value="false" /><!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 --><!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 --><!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 --><!-- 不理解该含义的前提下,不要随便复制该配置 --><!-- <property name="params" value="pageNum=start;pageSize=limit;" /> --></plugin>
</plugins>

然后在需要分页的查询之前,加上下面一句话:

PageHelper.startPage(pageNum,PAGE_SIZE);

Mybatis 中的sql标签

由于Mybatis是通过文本替换组装生成SQL语句的,所以不难发现它的插入和更新同样是静态的,对象里是null的插入也是null。你数据库的默认值不起作用而是得到null,那怎么解决这个问题呢?

<sql id="userColumn"><trim suffixOverrides=","><if test="id!=null">id,</if><if test="phone!=null">phone,</if><if test="email!=null">email,</if><if test="photo!=null">photo,</if></trim>
</sql><sql id="userValue"><trim suffixOverrides=","><if test="id!=null">#{id},</if><if test="phone!=null">#{phone},</if><if test="email!=null">#{email},</if><if test="photo!=null">#{photo},</if></trim>
</sql><insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">insert into user (<include refid="userColumn" />)values (<include refid="userValue"></include>)
</insert>

通过使用include和sql标签我们解决了这个问题。

Mybatis typeHandler

有时候我们常常想将Collection或者其他对象直接以Json字符串的形式存在数据库里而不是再开一张表,虽然普遍的观点是不赞同这种做法,但这种需求却是实际存在的。怎么才能在DAO中就将字符串和对象的转换做掉而不用交给上层显式地转换呢?

采用自定义的Typehandler就可以,下面给出一个例子

@MappedJdbcTypes(JdbcType.VARCHAR)
public class JSONHandler implements TypeHandler<Object> {/*** json数据和类名的分隔符号* */private static final char SPLIT = '/'; /*** json 转换成对象* */private Object jsonToObject(String json) throws RuntimeException{if (json == null) {return null;}int index = json.lastIndexOf(SPLIT);if (index < 0) {return null;}String key = json.substring(index + 1, json.length());json = json.substring(0, index);Class<?> cls = null;try {cls = Class.forName(key);} catch (ClassNotFoundException e) {throw new RuntimeException("序列化成json时找不到指定的类", e);}Object ob = JSON.parseObject(json, cls);return ob;}public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {if(parameter == null){ps.setString(i, null);return;}String json = JSON.toJSONString(parameter);json  = json + SPLIT + parameter.getClass().getName();ps.setString(i, json);}public Object getResult(ResultSet rs, String columnName) throws SQLException {String  json = rs.getString(columnName);return  jsonToObject(json);}public Object getResult(ResultSet rs, int columnIndex) throws SQLException {String json=rs.getString(columnIndex);return jsonToObject(json);}public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {String  json = cs.getString(columnIndex);return  jsonToObject(json);}}

首先设定处理的JDBCType,显然是变长字符,然后实现给定的接口,最后在Mybatis的配置文件中加上这么一句。

<typeHandlers><typeHandler  handler="sbeat.util.helper.JSONHandler" javaType="java.util.List"/><typeHandler  handler="sbeat.util.helper.JSONHandler" javaType="java.util.Map"/></typeHandlers>

将Map和List均交由该handler处理,但本人实测,这个好像并没有什么卵用,有用的是在Mapper.xml文件中显式指定,如下所示。

<insert>
insert (tags) values (#{tags,typeHandler=sbeat.util.helper.JSONHandler})
</insert>
<resultMap type="Employee" id="employeeResult"><result property="tags" column="tags" javaType="java.util.List"  typeHandler="sbeat.util.helper.JSONHandler"/>
</resultMap>

Mybatis 外键查询

外键查询需要使用resultMap的association标签,如下所示

  <resultMap type="Message" id="msgResultMap"><id property="id" column="id" /><result property="created" column="created" /><result property="title" column="title" /><result property="content" column="content" /><result property="has_read" column="has_read" /><result property="msgType" column="msgType" /><result property="receiverId" column="receiverId" />        <association property="sender" javaType="User"><id property="id" column="userId"/><result property="name" column="name"/><result property="phone" column="phone"/><result property="passwd" column="passwd"/><result property="photo" column="photo"/><result property="email" column="email"/><result property="userType" column="userType"/></association></resultMap>

Mybatis 多参数

在接口定义中使用@Params注解,并在XML中不定义paramType,如下所示

public List<Feedback> findByTradeId(@Param("tradeId") Long tradeId,@Param("ownerType") UserType ownerType);
   <select id="findByTradeId" resultType="Feedback">select * from feedback where tradeId=#{tradeId} <if test="ownerType!=null">AND ownerType=#{ownerType}</if>ORDER BY created DESC</select>

Mybatis 逗号问题

逗号的不注意往往是使用Mybatis中出现最多的失误,可以通过使用where和set一级trim标签来尽量避免,如下所示:

<trim suffixOverrides=","><if test="id!=null">id,</if><if test="phone!=null">phone,</if>
</trim>
<set><if test="phone!=null">phone=#{phone},</if><if test="name!=null">name=#{name},</if>
</set>
<where><if test="id!=null">id=#{id}</if><choose><when test="logic_delete!=null">AND logic_delete=#{logic_delete}</when><otherwise>AND   logic_delete=false</otherwise></choose><if test="name!=null"> AND name=#{name}</if>
</where>

转载于:https://my.oschina.net/suemi/blog/697185

Mybatis使用小札相关推荐

  1. 【转载】古龙·断章·小札[十二]:《多情剑客无情剑》

    古龙·断章·小札[十二]:<多情剑客无情剑> 作者:边城不浪 十年前,朝廷里的风流翰林,兵器谱上排名第三的探花郎黯然出关,展开自我放逐生涯.十年后,流放者归来. <多情剑客无情剑&g ...

  2. 【项目实战】 ---- 简单整合SpringBoot + MyBatis + Themyleaf小项目

    简单整合SpringBoot + MyBatis + Themyleaf小项目 一.项目环境搭建① 二.数据库表设计及项目环境② 三.图片验证码功能 四.用户注册功能 五.用户登录功能 六.员工的查询 ...

  3. STS安装配置及写的一个springboot整合mybatis的小demo

    新入职的猿,师傅给了一个小任务,用STS写一个springboot整合mybatis的小demo.由于之前没用过STS和eclipse,所以听到这个任务还是比较懵逼的,经过一天的摸索,慢慢的摸出了门道 ...

  4. 2.mybatis实用小插件

    我们在使用 MyBatis时,经常会用到一些单表查询,但是不得不在 *Mapper.xml 中写简单 sql,而如 selectUserBy(Long id) 这种情况,也需要在 Mapper.xml ...

  5. SpringBoot+MyBatis+微信小程序案例

    文章目录 1.在数据库创建表 2.创建SpringBoot项目 2.1 选择项目类型 2.2 设置组名包名等(根据个人需求更改) 2.3 选择依赖 2.3.1 选择Web依赖 2.3.2 选择MySQ ...

  6. Mybatis 查询小技巧

    在大部分的数据库设计中,为了方便数据表的维护和查询,都会用使用list+detail 的方式,例如:订单表+订单详情表.但是,这样在查询上,这个时候,用mybatis的级联查询,就回方便很多. 使用级 ...

  7. MyBatis使用小案例

    首先回顾一下MyBatis封装简化Dao层连接数据库操作的顺序. 首先MyBatis是一个引入的jar包,还有一些依赖包,可能用不到的jar包,一并引入就好了,再多引入一个Juntil.jar测试包( ...

  8. 文科出身敲出 Instagram,被小札“挤”走,建新冠追踪网站

    作者 | 年素清 责编 | 伍杏玲 出品 | 程序人生(ID:coder_life) Instagram以滤镜和图片质量为核心,是全球最火的在线图片及视频分享的社交应用软件之一,而Instagram也 ...

  9. Hibernate使用小札

    前言 Hibernate作为Java中最为流行的O/R映射框架,同时已经完全遵照JPA规范并作为其实现的一个超集,它能够帮助我们快速进行开发,从繁重的持久化层实现中脱离出来.本文将由浅入深为您带来一个 ...

最新文章

  1. hg 全局密码配置。
  2. 关于[入行几年后,你的未来应该在哪里]的思考
  3. java jli.dll_JVM、JRE、JDK之间的区别和联系,你居然还不知道?
  4. javascript编程题_如何开始使用JavaScript进行竞争性编程
  5. 神经网络与深度学习——TensorFlow2.0实战(笔记)(一)
  6. 【Java从0到架构师】SpringBoot - 入门_配置文件_YAML
  7. 深度学习:图像识别(匹配)方法|室内定位|论文与方法整理
  8. 未来时速——第一章 用事实的力量管理企业
  9. (十:2020.08.28)CVPR 2018 追踪之论文纲要(译)
  10. 微弱信号检测matlab代码,微弱信号检测实验报告.doc
  11. Windows登录FTP服务器方法
  12. vmware win7虚拟机运行异常卡顿问题解决
  13. 微信电子健康卡——身份证照片OCR接口
  14. NLP - Gensim
  15. MySQL索引 聚集索引
  16. Appium报错解决
  17. HDU 1208 Pascal‘s Travels
  18. 钉钉桌面版(dingtalk)介绍:支持Linux、Windows和macOS平台
  19. 1、direct X 的简介
  20. 三维重建 | 关键技术及建模流程综述「AI核心算法」

热门文章

  1. 极客标签前端特效资源精品大荟萃#002
  2. 安全狗+linux使用教程,三分钟秒懂!服务器linux安全狗安装详细教程
  3. Python版超市管理系统源代码,基于django+mysql
  4. 学习笔记-flowable
  5. freesurfer分割后的解剖文件.annot, 如何求解剖区域的三维坐标?如已知lh.HCP-MMP1.annot,如何求Glasser360的皮层三维坐标?
  6. pythonxy 2.7.5.0_叨叨记账下载-叨叨记账app安卓版下载v2.7.5.0-西西软件下载
  7. 亲密接触中国SaaS应用(中)
  8. 重要信息通知(短信通知+语音播报)解决方案
  9. div属性与span属性的区别
  10. 2017年IoT开发者调查报告