mybatis知识解惑

来源:互联网 发布:nginx conf配置详解 编辑:程序博客网 时间:2024/06/09 13:14

mybatis讲解:

  • Mybatis是一个apache持久层框架,它对jdbc的操作数据库的过程进行封装,只需关注sql本身,不需要花费精力去处理(注册驱动,创建连接,创建statement,手动设置参数,结果集的检索等)繁杂的过程代码。
  • Mybatis通过xml或者注解的方式将要执行的各种statement配制起来,通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。
  • 配制sql语句mapper.xml
  • 命名空间<mapper namespace="com.iotek.domain.StudentMapper"></mapper>
  •  <resultMap id="studentMap" type="com.iotek.domain.Student">
          <id property="sid" column="sid"/>
          <result property="sname" column="sname" />
          <result property="grade" column="grade"/>
          <result property="sex" column="sex"/>
          <result property="score" column="score"/>
       </resultMap>

  • 查询语句:其中$符号解析时会被解析成字段名,而#解析时会被解析成字符串,可以有效且动态的进行sql语句拼接。
  •   select id="findAllStudents" parameterType="com.iotek.domain.Student" resultMap="studentMap">
  •      select sid,sname,grade,sex,score from student where 1=1
          <if test="sname !=null and sname !=''">and sname like "%${sname}%"</if>
          <if test="grade !=null and grade !=''"> and grade = #{grade}</if>
          <if test="sex !=null and sex !=''">and sex = #{sex}</if>
          <if test="score !=null and score !=''">and score = #{score}</if>
         </select>

  • 插入语句
  • <insert id="insertStudent" parameterType="Student">
         <!-- 获取主键值,定义获取主键的sql,order:设置selectkey中的sql执行的顺序 -->
           <selectKey keyProperty="sid" order="AFTER" resultType="int">
              select LAST_INSERT_ID()
           </selectKey>
         insert into student(sname,grade,sex,score) values (#{sname},#{grade},#{sex},#{score})
      </insert>
  • 更新操作
  • <update id="updateStudent" parameterType="Student">
        update student
        <trim prefix="set" suffixOverrides=",">
          <if test="sname !=null and sname !=''">sname=#{sname},</if>
          <if test="grade !=null and grade !=''"> grade = #{grade},</if>
          <if test="sex !=null and sex !=''">sex = #{sex},</if>
          <if test="score !=null and score !=''">score = #{score},</if>
        </trim>
        where sid=#{sid}
      </update>
  • 删除操作
  • <!--collection:表示类型,这里参数是数组,就写成array,如果是集合,就写成list-->
      <delete id="deleteStudent">
       delete from student where sid in
       <foreach collection="list" item = "student" open="(" separator="," close=")">
       #{student.sid}
       </foreach>
      </delete>

  





原创粉丝点击