mybatis的mapper文件基础标签的使用

一、DQL

1.select

<select id="selectStudents" resultType="com.bjpowernode.domain.student">
    <!--要执行的 sql 语句-->
    select id,name,email,age from student order by id
</select>

select 语句属性配置细节:

属性描述取值默认
id 在这个模式下唯一的标识符,可被其它语句引用    
parameterType 传给此语句的参数的完整类名或别名    
resultType 语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)    
resultMap 引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)    
flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false true/false false
useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false true/false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 正整数 未设置
fetchSize 设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 正整数 驱动器决定
statementType statement,preparedstatement,callablestatement。预准备语句、可调用语句 STATEMENT、PREPARED、CALLABLE PREPARED
resultSetType forward_only、scroll_sensitive、scroll_insensitive 只转发,滚动敏感,不区分大小写的滚动 FORWARD_ONLY、SCROLL_SENSITIVE、SCROLL_INSENSITIVE 驱动器决定

 

<!--对于${}和#{}

${}是字符串替换,#{}是预编译处理,一般使用#{}防止sql注入
使用#{}之后, mybatis执行sql是使用的jdbc中的PreparedStatement对象
-->

mybatis会自动执行下列代码

<!--
         1. mybatis创建Connection , PreparedStatement对象
            String sql="select id,name, email,age from student where id=?";(每一个#{}都被认定为一个?,即占位符)
            PreparedStatement pst = conn.preparedStatement(sql);
            pst.setInt(1,1001);

         2. 执行sql封装为resultType="com.bjpowernode.domain.Student"这个对象
            ResultSet rs = ps.executeQuery();
            Student student = null;
            while(rs.next()){
               //从数据库取表的一行数据, 存到一个java对象属性中
               student = new Student();
               student.setId(rs.getInt("id));
               student.setName(rs.getString("name"));
               student.setEmail(rs.getString("email"));
               student.setAge(rs.getInt("age"));
            }

           return student;  //给了dao方法调用的返回值
-->

 

 注意:

select中的id要与接口中的方法名一致(DML也一样)

二、DML

 1.insert

<!-- 插入学生 -->  
<insert id="insertStudent" parameterType="StudentEntity">  
        INSERT INTO STUDENT_TBL (STUDENT_ID,  
                                          STUDENT_NAME,  
                                          STUDENT_SEX,  
                                          STUDENT_BIRTHDAY,  
                                          CLASS_ID)  
              VALUES   (#{studentID},  
                          #{studentName},  
                          #{studentSex},  
                          #{studentBirthday},  
                          #{classEntity.classID})  
</insert>

insert可以使用数据库支持的自动生成主键策略,设置useGeneratedKeys=”true”,然后把keyProperty 设成对应的列,就搞定了。比如说上面的StudentEntity 使用auto-generated 为id 列生成主键.

<insert id="insertStudent" parameterType="StudentEntity" useGeneratedKeys="true" keyProperty="studentID">

推荐使用这种用法。

另外,还可以使用selectKey元素。下面例子,使用MySQL数据库nextval(‘student’)为自定义函数,用来生成一个key。

<!-- 插入学生 自动主键-->  
<insert id="insertStudentAutoKey" parameterType="StudentEntity">  
    <selectKey keyProperty="studentID" resultType="String" order="BEFORE">  
            select nextval('student')  
    </selectKey>  
        INSERT INTO STUDENT_TBL (STUDENT_ID,  
                                 STUDENT_NAME,  
                                 STUDENT_SEX,  
                                 STUDENT_BIRTHDAY,  
                                 CLASS_ID)  
              VALUES   (#{studentID},  
                        #{studentName},  
                        #{studentSex},  
                        #{studentBirthday},  
                        #{classEntity.classID})      
</insert>

insert语句属性配置细节:

属性描述取值默认
id 在这个模式下唯一的标识符,可被其它语句引用    
parameterType 传给此语句的参数的完整类名或别名    
flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false true/false false
useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false true/false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 正整数 未设置
fetchSize 设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 正整数 驱动器决定
statementType statement、preparedstatement、callablestatement。预准备语句、可调用语句 STATEMENT、PREPARED、CALLABLE PREPARED
useGeneratedKeys 告诉MyBatis 使用JDBC 的getGeneratedKeys 方法来获取数据库自己生成的主键(MySQL、SQLSERVER 等关系型数据库会有自动生成的字段)。默认:false true/false false
keyProperty 标识一个将要被MyBatis设置进getGeneratedKeys的key 所返回的值,或者为insert 语句使用一个selectKey子元素。    

selectKey语句属性配置细节:

属性描述取值
keyProperty selectKey 语句生成结果需要设置的属性。  
resultType 生成结果类型,MyBatis 允许使用基本的数据类型,包括String 、int类型。  
order 可以设成BEFORE 或者AFTER,如果设为BEFORE,那它会先选择主键,然后设置keyProperty,再执行insert语句;如果设为AFTER,它就先运行insert 语句再运行selectKey 语句,通常是insert 语句中内部调用数据库(像Oracle)内嵌的序列机制。 BEFORE/AFTER
statementType 像上面的那样, MyBatis 支持STATEMENT,PREPARED和CALLABLE 的语句形式, 对应Statement ,PreparedStatement 和CallableStatement 响应 STATEMENT、PREPARED、CALLABLE

2.update

update语句属性配置细节:

属性描述取值默认
id 在这个模式下唯一的标识符,可被其它语句引用    
parameterType 传给此语句的参数的完整类名或别名    
flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false true/false false
useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false true/false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 正整数 未设置
fetchSize 设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 正整数 驱动器决定
statementType statement、preparedstatement、callablestatement。预准备语句、可调用语句 STATEMENT、PREPARED、CALLABLE PREPARED

 

3.delete

<delete id="deleteStudent" parameterType="StudentEntity">  
        DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID}  
</delete> 

 

 三、parameterType

<!--
      parameterType : dao接口中方法参数的数据类型。
        parameterType它的值是java的数据类型全限定名称或者是mybatis定义的别名
        例如:parameterType="java.lang.Integer"
             parameterType="int"

        注意:parameterType不是强制的,mybatis通过反射机制能够发现接口参数的数类型。
        所以可以没有。 一般我们也不写。
-->

四、传参

1.一个简单类型的参数

mybatis把java的基本数据类型和String都叫简单类型。

Student selectStudentById(@Param("studentId") Integer id);
<select id="selectStudentById" parameterType="java.lang.Integer" resultType="com.bjpowernode.domain.Student">
        select id,name, email,age from student where id=${studentId}<!--此处名称要与接口中方法中定义的名称相同-->
    </select>

2.多个参数

(1)第一种

多个参数: 命名参数,在形参定义的前面加入 @Param("自定义参数名称")

List<Student> selectMultiParam(@Param("myname") String name,
                                   @Param("myage") Integer age);

 

<!--多个参数,使用@Param命名(掌握)-->
    <select id="selectMultiParam" resultType="com.bjpowernode.domain.Student">
         select id,name, email,age from student where name=#{myname} or age=#{myage}
    </select>

 

(2)第二种

多个参数,使用java对象作为接口中方法的参数

 

List<Student> selectMultiStudent(Student student);
<!--多个参数, 使用java对象的属性值,作为参数实际值
        使用对象语法: #{属性名,javaType=类型名称,jdbcType=数据类型} 很少用。
                    javaType:指java中的属性数据类型。
                    jdbcType:在数据库中的数据类型。
                    例如: #{paramName,javaType=java.lang.String,jdbcType=VARCHAR}

        我们使用的简化方式: #{属性名}  ,javaType, jdbcType的值mybatis反射能获取。不用提供

    -->

 

<select id="selectMultiStudent" resultType="com.bjpowernode.domain.Student">
         select id,name, email,age from student where name=#{name} or age=#{age}<!--放入接口中参数对象所对应的属性名-->
    </select>

(3)第三种

多个参数-简单类型的,按位置传值

mybatis.3.4之前,使用 #{0} ,#{1}
mybatis.3.4之后 ,使用 #{arg0} ,#{arg1}

 List<Student> selectMultiPosition( String name,Integer age);
<!--多个参数使用位置(不推荐使用)-->
    <select id="selectMultiPosition" resultType="com.bjpowernode.domain.Student">
          select id,name, email,age from student where
          name = #{arg0} or age=#{arg1}
    </select>

(4)第四种

多个参数,使用Map存放多个值

List<Student> selectMultiByMap(Map<String,Object> map);
<!--多个参数,使用Map , 使用语法 #{map的key}(不推荐使用)-->
    <select id="selectMultiByMap" resultType="com.bjpowernode.domain.Student">
          select id,name, email,age from student where
          name = #{myname} or age=#{age1}
    </select>

五、动态SQL

 1.单独if标签

<!-- if
         <if:test="使用参数java对象的属性值作为判断条件,语法 属性=XXX值">
-->
<select id="selectStudentIf" resultType="com.bjpowernode.domain.Student">
        select id,name, age, email  from student
        where 
        <if test="name !=null and name !='' ">
           and name = #{name}
        </if>
        <if test="age > 0">
            or age > #{age}
        </if>
    </select>

注意:当地一个if条件不成立时 sql语句会变成为

select id,name, age, email from student where or age > #{age}

会出现语法错误,所以将其改进为

<select id="selectStudentIf" resultType="com.bjpowernode.domain.Student">
        select id,name, age, email  from student
        where id>0
        <if test="name !=null and name !='' ">
           and name = #{name}
        </if>
        <if test="age > 0">
            or age > #{age}
        </if>
    </select>

2.使用where标签

<!--
     where: <where> <if> <if>...</where>
     用来包含 多个<if>的, 当多个if有一个成立的,
     <where>会自动增加一个where关键字,
     并去掉 if中多余的 and ,or等
    -->

 

<select id="selectStudentWhere" resultType="com.bjpowernode.domain.Student">
        select id,name, age, email from student
        <where>
            <if test="name !=null and name !='' ">
                name = #{name}
            </if>
            <if test="age > 0">
                or age > #{age}
            </if>
        </where>
    </select>

 

3.foreach标签

<!--foreach使用1 , List<Integer>,集合中放数据类型
    collection:表示接口中的方法参数的类型, 如果是数组使用array , 如果是list集合使用list
     item:自定义的,表示数组和集合成员的变量,或者是属性名
     open:循环开始时的字符
     close:循环结束时的字符
    separator:集合成员之间的分隔符
-->
<select id="selectForeachOne" resultType="com.bjpowernode.domain.Student">
        select * from student where id in
        <foreach collection="list" item="myid" open="(" close=")" separator=",">
                  #{myid}
        </foreach>
</select>

 

 

<!--foreach使用2 , List<对象>,集合中放入对象-->
    <!--<select id="selectForeachTwo" resultType="com.bjpowernode.domain.Student">
        select * from student where id in
        <foreach collection="list" item="stu" open="("  close=")" separator=",">
                 #{stu.id}
        </foreach>

    </select>-->
    <!--foreach使用2 , List<对象>,集合中放入对象
    比上方的语法更灵活,自己写语法格式
    -->
<select id="selectForeachTwo" resultType="com.bjpowernode.domain.Student">
            <include refid="studentSql" />  where id in (
            <foreach collection="list" item="stu" >
                #{stu.id},
            </foreach>
            -1 )<!--此处减一是因为要去掉一个内容为逗号的字段-->
</select>

 

 

 

 

 

 

参考:https://www.cnblogs.com/yufeng218/p/6622644.html

posted @ 2021-11-03 20:36  夜柠檬  阅读(305)  评论(0编辑  收藏  举报