mybatis映射器和动态SQL总结

映射器

mybatis的映射器包含两部分:接口和映射文件。映射器的配置元素包括:select、insert、update、delete、sql、resultMap。mybatis映射文件的总结:
1、对于parameterType入参类型常用的有java.util.Map、java.lang.Integer等,可以采用系统自带的别名如byte、long、short、int、integer、float、double、boolean、string、date、map、list、decimal、bigdecimal等简化配置,也可以在mapper中自定义别名如

<typeAlias alias="HdPluginDO" type="com.abc.dal.dataObject.HdPluginDO"/>

传递多个参数的情况下,有如下传参方式:
1) 封装到map,用map接收;
2) 通过@Param("userId")传递,无需parameterType接收可直接使用;
3) 通过POJO封装同时用它接收。
建议5个以下参数采用第二种方式,5个以上采用第三种。返回类型一般有resultType和resultMap两种,insert、update、delete是不需要返回类型的,默认是整型。

2、resultMap用来映射结果集。type为映射的实体类,可以是类的全限定名或别名;id为此resultMap的标识。resultMap包含id、result、association 子元素,id和result用来将POJO的属性和SQL的列名做对应。
resutltMap的type属性设置为java.util.Map可以在dao中用Map<String,Object>接收数据

而实际上type为实体类的情况更常用,resultMap="BaseResultMap"表示返回类型为实体类

 association – 复杂类型的结合;多个结果合成的类型

<resultMap id="fieldMapper" type="com.cmcc.healthcare.pojo.hars.Appointmentrecord">
	<id property="id" column="ID" /><!---->
	<result property="hospitaluid" column="HOSPITALUID" /><!--医院主键id-->
	<association property="hospitalinfo" resultMap="hospitalinfoMap" /><!--医院信息-->
</resultMap>

3、主键回填,插入操作后返回自增Id,useGeneratedKeys用来控制是否打开自动生成主键这个功能,默认是false,当打开了这个开关,还要配置其属性keyProperty或keyColumn,告诉系统将生成的主键放入到哪个属性中。

<insert id="insertUserInfo" parameterType="com.cmcc.akso.entity.user.UserInfo" keyProperty= "memberId" useGeneratedKeys ="true">

4、字段为sql关键字如from,可使用反引号

INSERT IGNORE INTO t_user_info( member_code, enterprise_id, `from` ) VALUES ( #{memberCode}, #{enterpriseId}, #{from})

动态SQL

动态SQL的基本元素包括:if、set、where、bind、foreach、choose(when,otherwise)、trim(where,set)

1、<trim>用来截取并去掉特殊的字符串

prefix代表的是语句的前缀,而prefixOverrides代表的是那种字符串。

<insert id="insertSelective" parameterType="com.cmcc.akso.entity.user.UserInfo"
	useGeneratedKeys="true" keyProperty="memberId">
	insert into t_user_info
	<trim prefix="(" suffix=")" suffixOverrides=",">
		<if test="memberCode != null">MEMBER_CODE,</if>
		<if test="enterpriseId != null">enterprise_id,</if>
		<if test="updateTime != null">update_time</if>
	</trim>
	<trim prefix="values (" suffix=")" suffixOverrides=",">
		<if test="memberCode != null">#{memberCode,jdbcType=VARCHAR},</if>
		<if test="enterpriseId != null">#{enterpriseId,jdbcType=INTEGER},</if>
		<if test="updateTime != null">#{updateTime,jdbcType=TIMESTAMP}</if>
	</trim>
</insert>
<select id="findMusicIds" resultType="int">
	SELECT
	am.`music_id` AS musicId
	FROM
	t_album_music am
	<trim prefix="where" prefixOverrides="and">
		<if test="roleNo !=1 and roleNo!=''">
			AND role_no = #{roleNo}
		</if>
	</trim>
</select>

2、批量操作或in需要使用到<foreach>

<insert id="insertBatUserInfo" >
	insert ignore into t_user_info (
	MEMBER_CODE,
	DEPARTMENT_ID,
	UPDATE_TIME
	)
	values 
	<foreach collection="list" item="item" index="index" separator=",">
		(
		#{item.memberCode,jdbcType=VARCHAR},
		#{item.departmentId,jdbcType=INTEGER},
		#{item.updateTime,jdbcType=TIMESTAMP}
		)
	</foreach>
</insert>
<select id="getSysParamById" resultType="Base_SysParam" parameterType="String">
        SELECT * FROM BASE_SYSPARAM
        WHERE COMPID=#{compId}
            AND PARAMID in 
            <foreach collection="paramId" item="item" index="index" open="("
                separator="," close=")">
                #{item}
            </foreach>
        ORDER BY TYPE,PARAMID
</select>

3、数值比较时不允许出现">"、"&&"这样的字符因为这个mapper文件是xml格式的,使用<![CDATA[ ]]>这类符号不再进行解析 

<if test="endTime!=null"><![CDATA[ and end_time<= #{endTime}]]></if>
<if test="searchFlag != null &amp;&amp; searchFlag == 2">
	m.`music_name` AS resultName
</if>

4、选择判断<choose><when><otherwise>

<select id="getExistedMusicIds" resultType="java.lang.Integer">
	SELECT
	am.`music_id` AS musicId
	FROM
	t_album_music am
	WHERE 1=1
	<choose>
		<when test="roleNo !=1 and roleNo!=''">
			AND role_no = #{roleNo}
		</when>
		<when test="roleName !=null and roleName!=''">
			AND role_name like concat('%',#{roleName},'%')
		</when>
		<otherwise>
			AND note is not NULL 
		</otherwise>
	</choose>
</select>

5、以上示例如果不使用1=1,有时会出错,加入后又觉得多余,可以通过<where>去处理,当where的某个条件成立时,才会加入这个条件

<select id="getExistedMusicIds" resultType="java.lang.Integer">
	SELECT
	am.`music_id` AS musicId
	FROM
	t_album_music am
	<where>
		<if test="roleNo !=1 and roleNo!=''">
			AND role_no = #{roleNo}
		</if>
		<if test="roleName !=null and roleName!=''">>
			AND role_name like concat('%',#{roleName},'%')
		</if>
	</where>
</select>

6、更新操作使用<set>根据传入的参数动态更新指定的字段

<update id="updateRole" parameterType="role">
	update t_role
	<set>
		<if test="roleName != null and roleName !=''">
			role_name = #{roleName},
		</if>
		<if test="note != null and note !=''">
			note = #{note},
		</if>
	</set>
	where role_no = #{roleNo}
</update>

7、<bind>是通过ognl表达式定义的上下文变量,这样更加方便使用。用来替换mysql 的concat拼接和oracle中的||拼接。

<select id="getExistedMusicIds" resultType="java.lang.Integer">
	<bind name="pattern_roleName" value="'%'+roleName+'%'"></bind>
	SELECT
	am.`music_id` AS musicId
	FROM
	t_album_music am
	<where>
		<if test="roleNo !=1 and roleNo!=''">
			AND role_no = #{roleNo}
		</if>
		<if test="roleName !=null and roleName!=''">>
			AND role_name like #{pattern_roleName}
		</if>
	</where>
</select>

 

参考:mybatis官方文档

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis和Spring的集成非常方便,可以通过Spring提供的MapperFactoryBean来创建映射器。MapperFactoryBean是一个FactoryBean,用于创建MyBatis映射器。它可以自动创建映射器的实例,并使用Spring的注入机制自动将需要的依赖注入到映射器。 MapperFactoryBean的配置如下: ```xml <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.example.mybatis.UserMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> ``` 其,mapperInterface属性指定了映射器的接口类,sqlSessionFactory属性指定了MyBatisSqlSessionFactory实例。 在映射器接口,可以使用MyBatis提供的注解来构建动态SQL语句。例如: ```java public interface UserMapper { @Select("SELECT * FROM user WHERE username = #{username}") User findByUsername(String username); @Insert("INSERT INTO user (username, password) VALUES (#{username}, #{password})") void insert(User user); @Update("UPDATE user SET password = #{password} WHERE id = #{id}") void updatePassword(User user); @Delete("DELETE FROM user WHERE id = #{id}") void deleteById(long id); @SelectProvider(type = UserSqlProvider.class, method = "findUsers") List<User> findUsers(String username, String email); class UserSqlProvider { public String findUsers(String username, String email) { StringBuilder sql = new StringBuilder("SELECT * FROM user WHERE 1 = 1"); if (username != null) { sql.append(" AND username = #{username}"); } if (email != null) { sql.append(" AND email = #{email}"); } return sql.toString(); } } } ``` 在这个例子,使用@Select、@Insert、@Update和@Delete注解来构建静态SQL语句。使用@SelectProvider注解来构建动态SQL语句。其,@SelectProvider注解指定了SQL语句构建类的类型和方法名。 在UserSqlProvider类,使用StringBuilder来构建SQL语句。通过判断参数是否为空,来决定是否拼接相应的SQL语句片段。最后,返回完整的SQL语句。 以上就是MyBatis和Spring集成映射器动态SQL的简单介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值