Mybatis常用代码
以下使用的数据库是Mysql。
Mybatis字段类型映射
在resultMap 中定义数据库字段对应的字段类型。
<resultMap id="BaseResultMap" type="com.model.Order" >
<constructor >
<idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="order_id" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="create_date" jdbcType="DATE" javaType="java.util.Date" />
<arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
<arg column="action" jdbcType="TINYINT" javaType="java.lang.Byte" />
<arg column="total_price" jdbcType="DECIMAL" javaType="java.math.BigDecimal" />
</constructor>
</resultMap>
也可以使用property,如下所示
<resultMap id="BaseResultMap" type="com.model.Bill">
<result property="serialNo" column="fserial_no" jdbcType="VARCHAR"/>
<result property="type" column="ftype" jdbcType="INTEGER" />
<result property="invoiceAmount" column="finvoice_amount" jdbcType="DECIMAL" />
<result property="createTime" column="fcreate_time" jdbcType="TIMESTAMP"/>
<result property="invoiceDate" column="finvoice_date" jdbcType="DATE" />
</resultMap>
Mybatis动态Sql:
Mapper.xml如下:
<select id="selectOrderList" resultMap="BaseResultMap"
parameterType="com.model.Order">
select
<include refid="Base_Column_List" />
from t_order
where 1=1
<if test="id != null and id != '' ">and id = #{id,jdbcType=INTEGER} </if>
<if test="serialId != null and serialId != '' ">and serialId = #{serialId,jdbcType=VARCHAR} </if>
</select>
如果不想写1=1,也可以直接使用where标签。
where标签知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”或“OR”开头的,where 标签也知道如何将他们去除。
示例如下:
<select id="selectOrderList" resultMap="BaseResultMap"
parameterType="com.model.Order">
select
<include refid="Base_Column_List" />
from t_order
<where>
<if test="id != null and id !='' "> id = #{id,jdbcType=INTEGER} </if>
<if test="serialId != null and serialId != '' ">and serialId = #{serialId,jdbcType=VARCHAR} </if>
</where>
</select>
对应的Dao层如下:
此处直接将对象作为方法参数,假设参数为Order对象,传递到xml中的参数就包括了Order对象的属性变量,如上的id、serialId。
List<Order> selectOrderList(Order order);
如果仅有一两个变量,也可以直接传递变量,如下:
List<Order> selectOrderList( @Param("id ")Integer id , @Param("serialId ")String serialId );
Mybatis模糊查询:
模糊查询可以使用LIKE关键字和CONCAT()函数。
假设要查询的字段为product,从Dao层传递过来的参数为productName。
示例如下:
WHERE 1=1
<if test="productName!=null and productName!='' "> AND product LIKE CONCAT('%',#{ productName , jdbcType=VARCHAR },'%') </if>
Mybatis使用IN关键字指定条件范围:
IN关键字,需要通过foreach标签来实现。
其中,collection对应的是Dao层传递过来的参数(一般是集合或数组),
item是自己命名的,表示范围中的变量名称。
separator是指分隔符。index是指下标。
示例如下:
<select id="queryOrderUsedCount" resultType="java.lang.String">
SELECT count(*)
FROM t_check_account
WHERE 1=1
<if test=" clientIdList!=null">
AND fclient_id IN
<foreach collection="clientIdList" item="clientId" index="index" open="(" close=")" separator="," >
#{clientId}
</foreach>
</if>
</select>
对应的Dao层为:
String queryOrderListByCondition(@Param("clientIdList")String clientIdList);
Mybatis查询条件范围判断。
经常需要用Mysql查询在某个时间段的数据。
由于Mybatis中可能会将大于号>和小于号<视为标签,所以需要加上 字符。
示例如下:
WHERE 1=1
<if test="beginTime!=null and beginTime!='' "> <![CDATA[ AND t1.fcreate_time >= #{ beginTime , jdbcType=VARCHAR } ]]> </if>
<if test="endTime!=null and endTime!='' "> <![CDATA[ AND t1.fcreate_time < #{ endTime, jdbcType=VARCHAR } ]]> </if>
Mybatis多表查询。
多表查询,分为一对一、一对多、多对多。
简单的Sql语句,一对一可以通过association标签实现,一对多和多对多通过collection标签实现。
详情见: https://www.cnblogs.com/expiator/p/9328338.html
复杂的Sql语句,可以直接设置返回的resultMap为Map,通过Map的键值对解析。
示例如下:
<select id="queryOrderList" resultType="java.util.HashMap">
SELECT
t2.allnum,
t2.username
FROM t_order t1
LEFT JOIN t_order_detail t2 ON t2.orderid = t1.id
WHERE 1=1
<if test="beginTime!=null and beginTime!='' "> <![CDATA[ AND t1.fcreate_time >= #{ beginTime , jdbcType=VARCHAR } ]]> </if>
<if test="endTime!=null and endTime!='' "> <![CDATA[ AND t1.fcreate_time < #{ endTime, jdbcType=VARCHAR } ]]> </if>
<if test="productName!=null and productName!='' "> AND t1.productname LIKE CONCAT('%',#{ productName , jdbcType=VARCHAR },'%')</if>
</select>
对应的Dao层如下:
List<Map<String,Object>> queryOrderList( @Param("productName")String productName ,
@Param("beginDate") String beginDate, @Param("endDate") String endDate );
返回类型为List<Map<String,Object>>,遍历List,获取Map中键对应的值即可。
Controller层如下所示:
//....
//忽略其他无关逻辑
List<Map<String,Object>> orderList=orderService.queryOrderList( productName, beginDate , endDate);
if( orderList.size()>0 ) {
//取第一行的订货信息
Map<String, Object> orderMap=orderList.get(0);
//Object转换为Integer类型
Integer allNum = (Integer) orderMap.get("allnum") ;
//Object转换为String类型
String userName = String.valueOf( orderMap.get("username ") ) ;
}
Mybatis插入数据
对应sql语句:
insert into 表名 (字段1,字段2,字段3) values (字段1的值,字段2的值,字段3的值);
xml如下所示:
其中的useGeneratedKeys="true" keyProperty="id"表示主键自动产生。
而clientId 、clientSecret 、clientName 、eCheck 都是属于Developer类的属性。在Dao层传递对象过来后,可以使用该对象的属性。
<insert id="insert" parameterType="com.model.Developer" useGeneratedKeys="true" keyProperty="id">
insert into t_bd_developer
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="clientId != null">client_id,</if>
<if test="clientSecret != null">client_secret, </if>
<if test="clientName != null">client_name,</if>
<if test="eCheck != null">isCheck,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="clientId != null">#{clientId,jdbcType=VARCHAR},</if>
<if test="clientSecret != null">#{clientSecret,jdbcType=VARCHAR}, </if>
<if test="clientName != null">#{clientName,jdbcType=VARCHAR},</if>
<if test="eCheck != null">#{eCheck,jdbcType=INTEGER},</if>
</trim>
</insert>
Dao层则如下所示:
int insert(Developer developer);
Mybatis处理日期
当jdbcType="DATE"类型时,返回的时间只有年月日(yyyy-MM-dd)的,当jdbcType=“TIMESTAMP”的时候,返回的时间是年月日和时分秒(yyyy-MM-dd HH:mm:ss)
比如createDate为 2019-04-17,createTime为 2019-04-17 22:25:28,处理如下:
<resultMap id="BaseResultMap" type="com.model.Bill">
<result property="createDate" column="fcreate_date" javaType="Date" jdbcType="DATE"/>
<result property="createTime" column="fcreate_time" javaType="Date" jdbcType="TIMESTAMP" />
</resultMap>
参考资料:
https://www.cnblogs.com/expiator/p/9328338.html
https://blog.csdn.net/u011781521/article/details/79669180
https://www.cnblogs.com/cyttina/p/3894428.html
Mybatis常用代码的更多相关文章
- Mybatis常用xml
工作中mybatis常用的xml代码 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ma ...
- MyBatis - 常用标签与动态Sql
MyBatis常用标签 ● 定义sql语句:select.insert.delete.update ● 配置JAVA对象属性与查询结构及中列明对应的关系:resultMap ● 控制动态sql拼接:i ...
- GCD 常用代码
GCD 常用代码 体验代码 异步执行任务 - (void)gcdDemo1 { // 1. 全局队列 dispatch_queue_t q = dispatch_get_global_queue(0, ...
- 转--Android实用的代码片段 常用代码总结
这篇文章主要介绍了Android实用的代码片段 常用代码总结,需要的朋友可以参考下 1:查看是否有存储卡插入 复制代码 代码如下: String status=Environment.getE ...
- 刀哥多线程之03GCD 常用代码
GCD 常用代码 体验代码 异步执行任务 - (void)gcdDemo1 { // 1. 全局队列 dispatch_queue_t q = dispatch_get_global_queue(0, ...
- jquery常用代码集锦
1. 如何修改jquery默认编码(例如默认GB2312改成 UTF-8 ) 1 2 3 4 5 $.ajaxSetup({ ajaxSettings : { contentT ...
- Mysql:常用代码
C/S: Client Server B/S: Brower Server Php主要实现B/S .net IIS Jave TomCat LAMP:L Mysql:常用代码 Create table ...
- javascript常用代码大全
http://caibaojian.com/288.html 原文链接 jquery选中radio //如果之前有选中的,则把选中radio取消掉 $("#tj_cat .pro_ca ...
- Android 常用代码大集合 [转]
[Android]调用字符串资源的几种方法 字符串资源的定义 文件路径:res/values/strings.xml 字符串资源定义示例: <?xml version="1.0&q ...
随机推荐
- window7 修改docker安装的machine 位置
win7下安装docker ,默认的machine location 是在C:\users\xx\.docker\machine\machines 下面,为了不占用系统盘,想修改盘符位置 google ...
- 【dbdiff】数据库比对工具安装
安装git 忽略 安装visual c++组件(和mysql workbench需要的一样) https://www.microsoft.com/en-us/download/details.aspx ...
- bzoj5107: [CodePlus2017]找爸爸
Description 小A最近一直在找自己的爸爸,用什么办法呢,就是DNA比对.小A有一套自己的DNA序列比较方法,其最终目标是最 大化两个DNA序列的相似程度,具体步骤如下:1.给出两个DNA序列 ...
- 2.NB-IoT及通信协议
NB-IoT 1.什么是NB-IoT? NB-IoT全称窄带物联网(Narrow Band IOT),构建于蜂窝网络,只消耗大约180KHz的带宽,可直接部署于GSM网络.UMTS网络或LTE网络,以 ...
- udt通信java
udt协议是什么? 简单的是udp重发 经过上次的修正,重新测试,修复,测试各种环境,再次查找出源码错误,重新修正 修正内容在git中的修正说明中 同时针对之后的应用,对封装的代码也做了修改和重构 代 ...
- Koa,React和socket.io
安装 socket.io/socket.io-client 基本用法 首先koa和socket.io代码片段 const server = require('http'). const server ...
- Android开发 集成极光推送中的问题
AndroidManifest.xml清单文件报错: cn.jpush.android.service.DataProvider@exported value=(true)报错,解决如下: 根据报错行 ...
- es6 和 python 语法比较
http://www.linchaoqun.com/html/cms/content.jsp?id=1509528630774 Python3笔记:Python与ECMAScript部分语法对比 ht ...
- windows文件名格式的中文+数字混合字符串排序
记录一下 [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] private static extern int StrCm ...
- 用tar命令把目标压缩包解压到指定位置
linux下tar命令解压到指定的目录 : #tar zxvf /bbs.tar.zip -C /zzz/bbs //把根目录下的bbs.tar.zip解压到/zzz/bbs下,前提要保证存在/ ...