Mybatis常用操作

mybatis是一款持久层的框架,以下记录mybatis中看到的常见操作

<mapper namespace="com.ruoyi.system.mapper.SysUserMapper">
</mapper> 
/**
  *mapper 标签属于映射文件的根标签
  *namespace 用于提供访问该映射文件的标识名称,该名称必须以dao接口的完整路径命名
**/

mapper映射配置,该文件适用于java程序中存放执行的sql脚本

  1. 必须接口dao中的接口存在
  2. 命名空间必须同dao的接口名称相同
  3. 每个模块必须提供独立的映射文件

CRUD操作

<resultMap type="SysUser" id="SysUserResult">
	<id     property="userId"       column="user_id"      />
	<result property="deptId"       column="dept_id"      />
	<result property="loginName"    column="login_name"   />
	<result property="userName"     column="user_name"    />
</resultMap>


resultMap 表示返回结果集
type 表示转换的对象
id  提供给其他SQL引用的名称
  • 添加操作
 	<insert id="insertUser" parameterType="SysUser" useGeneratedKeys="true" keyProperty="userId">
 		insert into sys_user(
 			<if test="userId != null and userId != 0">user_id,</if>
 			<if test="deptId != null and deptId != 0">dept_id,</if>
 			<if test="loginName != null and loginName != ''">login_name,</if>
 			<if test="userName != null and userName != ''">user_name,</if>
 			create_time
 		)values(
 			<if test="userId != null and userId != ''">#{userId},</if>
 			<if test="deptId != null and deptId != ''">#{deptId},</if>
 			<if test="loginName != null and loginName != ''">#{loginName},</if>
 			<if test="userName != null and userName != ''">#{userName},</if>
 			sysdate()
 		)
	</insert>

id ==> java程序调用数据库操作的方法名称

parameterType ==> 传入当前方法中的参数类型 (对象/基本数据类型)

useGeneratedKeys ==>非必要操作参数,当值为true时,在执行添加记录之后可以获取到数据库自动生成的主键ID。

keyProperty ==> 与useGeneratedKeys一起使用,表示对应的主键的对象
  • 删除操作
	<delete id="deleteUserById" parameterType="Long">
 		update sys_user  where user_id = #{userId}
 	</delete>

 

  • 修改操作
 	<update id="updateUser" parameterType="SysUser">
 		update sys_user
 		<set>
 			<if test="deptId != null and deptId != 0">dept_id = #{deptId},</if>
 			<if test="loginName != null and loginName != ''">login_name = #{loginName},</if>
 			<if test="userName != null and userName != ''">user_name = #{userName},</if>
 			<if test="userType != null and userType != ''">user_type = #{userType},</if>
 			update_time = sysdate()
 		</set>
 		where user_id = #{userId}
	</update>
 	
  • 查询操作
	<select id="checkLoginNameUnique" parameterType="String" resultType="int">
		select count(1) from sys_user where login_name=#{loginName}
	</select>

 

当一个查询语句用的多的时候,我们还可以写一个固定的SQL  然后通过<include refid="。。。"/> 来引用。作用相当于 * ,

selectUserVo是固定的几个字段,而用*号的话会降低查询效率,因为后期数据库的字段会不断增加。

    <sql id="selectUserVo">
        select  u.user_id, u.dept_id, u.login_name, u.user_name
		from sys_user u
	    left join sys_user_role ur on u.user_id = ur.user_id
    </sql>

	<select id="selectUserByEmail" parameterType="String" resultMap="SysUserResult">
	    <include refid="selectUserVo"/>
		where u.email = #{email}
	</select>

 

我们在项目中偶尔会遇到需要动态生成sql语句的查询条件,这个时候我们就可以用mybatis的foreach了

foreach元素的属性主要有item,index,collection,open,separator,close。

  • item:集合中元素迭代时的别名,必选。
  • index:在list和数组中,index是元素的序号,在map中,index是元素的key,可选
  • open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。可选
  • separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。可选。
  • close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。可选。
  • collection: 要做foreach的对象,作为入参时,List对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果User有属性List ids。入参是User对象,那么这个collection = "ids".如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"

在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况: 

  • 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list .
  • 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array .
  • 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.
 	<delete id="deleteUserByIds" parameterType="Long">
 		update sys_user set del_flag = '2' where user_id in
        <foreach collection="array" item="userId" open="(" separator="," close=")">
 			#{userId}
        </foreach> 
 	</delete>

对应的java代码块 

    /**
     * 批量删除用户信息
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(String ids) throws BusinessException
    {
        Long[] userIds = Convert.toLongArray(ids);
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
        }
        return userMapper.deleteUserByIds(userIds);
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值