`

myibatis mapper 表达式

阅读更多

Mybatis实用Mapper SQL汇总示例

Mybatis作为一个非常好用的持久层框架,相关资料真的是少得可怜,所幸的是官方文档还算详细。本博文主要列举一些个人感觉比较常用的场景及相应的Mapper SQL写法,希望能够对大家有所帮助。

不少持久层框架对动态SQL的支持不足,在SQL需要动态拼接时非常苦恼,而Mybatis很好地解决了这个问题,算是框架的一大亮点。对于常见的场景,例如:批量插入/更新/删除,模糊查询,多条件查询,联表查询,都有非常好的支持。Mybatis的动态SQL生成功能实际使用的是OGNL表达式语言,理解OGNL表达式对动态SQL的使用会有很大程度的帮助。

下面直接上示例:

一、批量插入/更新/删除

批量操作主要使用的是Mybatis的foreach,遍历参数列表执行相应的操作,所以批量插入/更新/删除的写法是类似的,只是SQL略有区别而已。MySql批量操作需要数据库连接配置allowMultiQueries=true才可以。
(1)批量插入 

<insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="true">
		<foreach close="" collection="list" index="index" item="item" open="" separator=";">
			insert into user (name, age,dept_code) values
			(#{item.name,jdbcType=VARCHAR},
			#{item.age,jdbcType=INTEGER},
			 #{item.deptCode,jdbcType=VARCHAR}
			)
		</foreach>
	</insert>

 

上面演示的是MySql的写法,因为MySql支持主键自增,所以直接设置useGeneratedKeys=true,即可在插入数据时自动实现主键自增。实际Mysql还有另外一种写法,就是拼接values的写法,这种方法我测试过比多条insert语句执行的效率会高些。不过需要注意一次批量操作的数量做一定的限制。具体写法如下: 

<insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="true">
		insert into user (name, age,dept_code) values
		<foreach collection="list" index="index" item="item" open="" close="" separator=",">
			(#{item.name,jdbcType=VARCHAR},
			#{item.age,jdbcType=INTEGER},
			 #{item.deptCode,jdbcType=VARCHAR}
			)
		</foreach>
	</insert>

 对于Oracle不支持主键自增,需要序列替换,所以在SQL写法上略有不同,需要在select语句前加个 <selectKey>...</selectKey>告知Mybatis主键如何生成。

 

 (2)批量更新 

<update id="batchUpdate" parameterType="java.util.List">
		<foreach close="" collection="list" index="index" item="item" open="" separator=";">
			update user set name=#{item.name,jdbcType=VARCHAR},age=#{item.age,jdbcType=INTEGER}
			where id=#{item.id,jdbcType=INTEGER}
		</foreach>
	</update>

 

(3)批量删除 

<delete id="batchDelete" parameterType="java.util.List">
		<foreach close="" collection="list" index="index" item="item" open="" separator=";">
			delete from user
			where id=#{item.id,jdbcType=INTEGER}
		</foreach>
	</delete>

 

二、模糊查询 

<select id="selectLikeName" parameterType="java.lang.String" resultMap="BaseResultMap">
		select
		<include refid="Base_Column_List" />
		from user
		where name like CONCAT('%',#{name},'%' ) 
	</select>

 上面的模糊查询语句是Mysql数据库的写法示例,用到了Mysql的字符串拼接函数CONCAT,其它数据库使用相应的函数即可。

 

三、多条件查询

多条件查询常用到Mybatis的if判断,这样只有条件满足时,才生成对应的SQL。 

<select id="selectUser" parameterType="map" resultMap="BaseResultMap">
		select
		<include refid="Base_Column_List" />
		from user
		<where>
			<if test="name != null">
				name = #{name,jdbcType=VARCHAR}
			</if>
			<if test="age != null">
				and age = #{age,jdbcType=INTEGER}
			</if>
		</where>
	</select>

 

四、联表查询

联表查询在返回结果集为多张表的数据时,可以通过继承resultMap,简化写法。例如下面的示例,结果集在User表字段的基础上添加了Dept的部门名称。 

<resultMap id="ExtResultMap" type="com.research.mybatis.generator.model.UserExt" extends="BaseResultMap">
   	 <result column="name" jdbcType="VARCHAR" property="deptName" />
  </resultMap>
	
	<select id="selectUserExt" parameterType="map" resultMap="ExtResultMap">
		select
		 	u.*, d.name
		from user u inner join dept d on u.dept_code = d.code
		<where>
			<if test="name != null">
				u.name = #{name,jdbcType=VARCHAR}
			</if>
			<if test="age != null">
				and u.age = #{age,jdbcType=INTEGER}
			</if>
		</where>
	</select>

 

 上述示例皆在MySql数据库下测试通过,这里限于篇幅,相应的代码及测试类我就不贴上来了。完整的代码及测试类,可以查看我的Github项目地址:https://github.com/wdmcygah/research-mybatis。主要是UserService和UserServiceTest两个类,仓库里面还有些与本博文不相关的代码,注意区分。

 

 

1 楼 yin_bp 1 小时前  
楼主可以对比一下bboss持久层类似功能的做法:
1.批量增删改-真正采用jdbc的预编译批处理来实现,性能杠杠的,sql语句只需要配置一条,无需foreach
 
这里以更新为实例,新增和删除类似:
<property name="updateuser">
		<![CDATA[ update user set name=#[name],age=#[age]where id=#[id]
]]>
	</property>


执行批处理操作
List<User> users =...;
executor.updateBeans("updateuser",users);//在bboss默认数据源上执行 ,多个用户的更新操作以预编译批处理的模式执行  
executor.updateBeans(dbname,"updateuser",users);//在指定的bboss数据源上执行 

参考文档:
bboss预编译批处理api使用介绍

2.模糊查询
以下是mysql数据库依赖模式:
<property name="selectGroupInfoByNames">
		<![CDATA[ select *  
from user   
where name like CONCAT('%',#[name]'%' )    
]]>
	</property>


Map<String, String> condition = new HashMap<String, String>();//定义包含变量的map对象,key为变量名称,value为变量值   
condition.put("name", "john");  
List<CandidateGroup> list = executor.queryListBean(CandidateGroup.class,   
               "selectGroupInfoByNames", condition _);//执行查询 


以下是数据库无关模式
<property name="selectGroupInfoByNames">
		<![CDATA[ select *  
from user   
where name like #[name]
]]>
	</property>


Map<String, String> condition = new HashMap<String, String>();//定义包含变量的map对象,key为变量名称,value为变量值   
condition.put("name", "%john%");  
List<CandidateGroup> list = executor.queryListBean(CandidateGroup.class,   
               "selectGroupInfoByNames", condition _);//执行查询 


3.动态sql
bboss 动态sql使用foreach循环示例   
bboss持久层框架动态sql语句配置和使用 
bboss 持久层sql语句中一维/多维数组类型变量、list变量、map变量、bean对象变量使用说明
2 楼 yin_bp 42 分钟前  
上面的例子都是bboss 持久层or maping的模式,接下来看一个原生sql批处理删除操作的玩法。
sql配置:
<property name="deleteByKey">
		<![CDATA[
			delete from TD_APP_BOM where id=?
		]]>
	</property>

java代码:
/**
	 * 用同样的sql只删一条记录,根据主键删除台账信息
	 * @throws AppBomException 
	 */
	public boolean delete(String id) throws AppBomException {
		try {
			executor.delete("deleteByKey", id);
		} catch (Throwable e) {
			throw new AppBomException("delete appbom failed::id="+id,e);
		}
		return true ;
	}

	/**
	 * 用同样的sql批量删除记录,受事务管理控制,如果有记录删除失败,则全部回滚之前的记录,当然也可以不要事务,也就是出错后
	 * 前面的记录成功、后面的记录不入库
	 * @param beans
	 * @return
	 * @throws AppBomException 
	 */
	public boolean deletebatch(String ... ids) throws AppBomException {
		TransactionManager tm = new TransactionManager();
		try {
			tm.begin();
			executor.deleteByKeys("deleteByKey", ids);
			tm.commit();
		} catch (Throwable e) {
			
			throw new AppBomException("batch delete appbom failed::ids="+ids,e);
		}
		finally
		{
			tm.release();
		}

		return true;
	}
//不要事务的模式
	public boolean deletebatch(String ... ids) throws AppBomException {
		
		try {
			
			executor.deleteByKeys("deleteByKey", ids);
			
		} catch (Throwable e) {
			
			throw new AppBomException("batch delete appbom failed::ids="+ids,e);
		}
		

		return true;
	}
分享到:
评论

相关推荐

    MyBatis SonarQube Plugin自定义规则用于检查 MyBatis Mapper 文件中的风险 SQL.zip

    mybatis动态sql 1.什么是动态SQL? Mabits是一个Java持久化框架,它提供了动态SQL的功能。动态SQL是一种根据不同条件动态生成SQL语句的技术。在Mabits中,动态SQL通常是通过使用一组特殊的标签和代码块来实现的,...

    根据MyBatis或iBatis的SQLMapper文件反向生成数据库表

    根据MyBatis或iBatis的SQLMapper文件解析生成数据库表,通常是指通过解析MyBatis或iBatis的SQLMapper文件中的SQL语句,然后根据这些SQL语句来生成对应的数据库表结构。这样的需求可能源于需要将已有的SQLMapper文件...

    springmybatis

    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt; &lt;mapper namespace="com.yihaomen.mybatis.models.UserMapper"&gt; select * from `user` where id...

    mybatis-plus框架的拓展包,基础上做了进一步的轻度封装增强内容:免手写Mapper数据自动填充冗余数据自动更 .zip

    mybatis动态sql 1.什么是动态SQL? Mabits是一个Java持久化框架,它提供了动态SQL的功能。动态SQL是一种根据不同条件动态生成SQL语句的技术。在Mabits中,动态SQL通常是通过使用一组特殊的标签和代码块来实现的,...

    topfox快速开发框架

    热加载 支持在不使用devtools/jrebel的情况下, 热加载 mybatis的mapper文件 内置全局、局部拦截插件:提供delete、update 自定义拦截功能 拥有预防Sql注入攻击功能 无缝支持spring cloud: 后续提供分布式调用的例子

    topfox快速开发平台例子 topfox-sample.zip

    - **热加载** 支持在不使用devtools/jrebel的情况下, 热加载 mybatis的mapper文件 - 内置全局、局部拦截插件:提供delete、update 自定义拦截功能 - **拥有预防Sql注入攻击功能** - **无缝支持spring cloud**: 后续...

    code-engine.zip代码生成器

    适用于所有用到springmvc+mybatis的项目,从controller到mapper.xml,全面覆盖,解放你的双手

    基于框架的Web开发-使用mybaits逆向工程改写.docx

    (1) 使用mybatis-generator生成逆向工程,即由数据表自动生成实体类、dao接口、**mapper.xml映射文件。 (2) 用生成的实体类、dao接口、**mapper.xml替换原来estore-ssm工程中的对应部分。 (3) 有了自动生成的一套...

    单点登录源码

    Spring+SpringMVC+Mybatis框架集成公共模块,包括公共配置、MybatisGenerator扩展插件、通用BaseService、工具类等。 &gt; zheng-admin 基于bootstrap实现的响应式Material Design风格的通用后台管理系统,`zheng`...

    SpringBoot笔记-下篇.pdf

    整理自尚硅谷视频教程springboot高级篇,并增加部分springboot2.x的内容 一、Spring Boot与缓存 一、JSR107 Java Caching定义了5个核心接口,分别是...1)、@MapperScan指定需要扫描的mapper接口所在的包

Global site tag (gtag.js) - Google Analytics