自定义SQL语句中需要关注的名词含义及其用法

  • mapper中的namespace的含义:namespace命名空间是指的mapper接口的全路径名,目的是为了保证SQL语句的唯一性。
    <mapper namespace="com.mapper.XXXMapper">
  • resultMap以及其中type和id的含义:resultMap代表返回值数据库类型和Java类型的映射,type值为返回一个pojo对象,id为一个id结果,标记出作为id的结果可以帮助提高整体性能。
<resultMap type="Pojo" id="PojoResult">
    <result property="属性名"    column="元素名"    />
</resultMap>
  • sql标签代表sql语句片段(可以是一条select语句,也可以是其中的id,type,若为后者,需要将select语句补充完整)
<sql id="selectPojoVo">
    select id, type
    from tablename(表名)
</sql>
  • select语句
<select id="selectPojoById" parameterType="Long" resultMap="PojoResult">
   	<include refid="selectPojoVo"/>
        where id = #{id}
</select>
<select id="selectPojoList" parameterType="Pojo" resultMap="PojoResult">
    <include refid="selectPojoVo"/>
    <where>
        <if test="id != null "> and id = #{id}</if>
        <if test="type != null "> and type = #{type}</if>
    </where>
</select>
  • insert语句
<insert id="insertPojo" parameterType="Pojo" useGeneratedKeys="true" keyProperty="id">
    insert into tablename(表名)
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id != null">id,</if>
        <if test="type != null">type,</if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="id != null">#{id},</if>
        <if test="type != null">#{type},</if>
    </trim>
</insert>
  • update语句
<update id="updatePojo" parameterType="Pojo">
    update tablename(表名)
    <trim prefix="SET" suffixOverrides=",">
        <if test="type != null">type = #{type},</if>
    </trim>
    where id = #{id}
</update>
  • delete语句
<delete id="deletePojoById" parameterType="Long">
    delete from tablename(表名) where id = #{id}
</delete>
<delete id="deletePojoByIds" parameterType="String">
    delete from tablename(表名) where id in
    <foreach item="id" collection="array" open="(" separator="," close=")">
        #{id}
    </foreach>
</delete>
  • 对集合的处理(数组,list,map)
  1. foreach元素的属性主要有 item,index,collection,open,separator,close。
  2. collection标识参数中的属性,1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list,2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array。
  3. item表示集合中每一个元素进行迭代时的别名,
    index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
    open表示该语句以什么开始,
    separator表示在每次进行迭代之间以什么符号作为分隔符,
    close表示以什么结束。
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐