MyBatis(2):MyBatis标签以及对应的属性用法讲解

来源:互联网 发布:2016淘宝规则好评返现 编辑:程序博客网 时间:2024/05/19 02:23

通过上一章的讲解,大家应该对MyByatis的基本用法有了一定的了解。这一章主要是讲一下MyBatis的各种标签以及对应的属性,它们的用法以及用的时候应该注意一些什么!下面的讲解时结合当前主流框架(Spring+Spring MVC+MyBatis)以及Oracle数据库进行介绍。其他情况可以参照,不同框架不同数据库可能会存在某些差异。本章将向user_table表中加一个学生主键studentId,student_table表如下

create table student_table(    studentId          int     not null,    studentName        varchar(20) not null,    constraint userId primary key ( userId  )  );  

讲解上面内容之前需要先了解一下jdbcType和javaType:
JDBC Type类型            Java Type类型  
CHAR                 String  
VARCHAR              String  
LONGVARCHAR          String  
NUMERIC              java.math.BigDecimal  
DECIMAL              java.math.BigDecimal  
BIT                  boolean  
BOOLEAN              boolean  
TINYINT              byte  
SMALLINT             short  
INTEGER              int  
BIGINT               long  
REAL                 float  
FLOAT                double  
DOUBLE               double  
BINARY               byte[]  
VARBINARY            byte[]  
LONGVARBINARY        byte[]  
DATE                 java.sql.Date  
TIME                 java.sql.Time  
TIMESTAMP            java.sql.Timestamp  
CLOB                 Clob  
BLOB                 Blob  
ARRAY                Array  
DISTINCT             mapping of underlying type  
STRUCT               Struct  
REF                  Ref  
DATALINK            java.net.URL[color=red][/color]  
对应接口的xml文件UserMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  <mapper namespace="com.mybatis.mapper.UserMapper" >  <resultMap id="UserVO" type="com.mybatis.VO.UserVO">          <id property="userId" column="userId" javaType="java.lang.Integer"></id>          <result property="userName" column="userName" javaType="java.lang.String"></result>          <result property="userAge" column="userAge" javaType="java.lang.String"></result>          <result property="userPhone" column="userPhone" javaType="java.lang.String"></result>  <association column="studentId" property="studentId" resultMap="com.mybatis.mapper.StudentMapper.StudentVO"/>    </resultMap>  </mapper><?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  <mapper namespace="com.mybatis.mapper.StudentMapper" >  <resultMap id="StudentVO" type="com.mybatis.VO.StudentVO">          <id property="studentId" column="studentId" javaType="java.lang.Integer"></id>          <result property="studentName" column="studentName" javaType="java.lang.String"></result>       </resultMap>  </mapper>


UserMapper.xml 是对UserMapper.java 接口的实现。他们之间的关联通过UserMapper.xml 中的<mapper ></mapper> 标签中的namespace属性实现绑定,namespace的属性值为mapper所在的包路径
association :先知道怎么用就行,后面会详细介绍用法
一、insert,delete,update,select标签以及对应的属性

1.insert标签
insert标签分为两种情况:
一种是数据库(如MySQL,SQLServer)支持自动生成主键,另一种是数据库(如Oracle)不支持自动生成主键。下面是不自动生成主键,如果为自动生成主键userId不用插入。

<insert id="save" parameterType="com.mybatis.VO.UserVO">INSERT INTO user_table(userId, userName,userAge,userPhone,studentId)values (#{userId,jdbcType=INTEGER},#{userName,jdbcType=CHAR},#{userAge,jdbcType=INTEGER},#{userPhone,jdbcType=VARCHAR},#{studentId.pk,jdbcType=CHAR})</insert>

id:id是命名空间中的唯一标示符,可被用来代表这条语句。一个命名空间(namespace)对应一个接口,这个id也应该对应接口里的某个方法(必    须一致),不一致会报错!parameterType:参数类型;
statementType:取值范围STATEMENT,PREPARED(默认值),CALLABLE;
flushCache:取值范围true(默认值)|false,设置执行该操作后是否会清空二级缓存和本地缓存;
timeout:默认为unset(依赖jdbc驱动器的设置),设置执行该操作的最大时限,超时将抛异常;

批量插入方式

<insert id="save" parameterType="java.util.List">INSERT INTO user_table(userId, userName,userAge,userPhone)<foreach collection="list" item="item" index="index" open="(" close=")" separator="union all">SELECT #{item.userId}, #{item.userName},   #{item.userAge}, #{item.userPhone} FROM DUAL</foreach></insert>

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
 
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成
2.delete标签

<delete id="delete" parameterType="String">delete from user_table where userId=#{userId,jdbcType=CHAR}</delete>


批量删除

<delete id="delete" parameterType="java.util.List">delete from user_table where userId in<foreach collection="list" item="item" index="index" open="(" separator="," close=")">        #{item,jdbcType=CHAR}    </foreach></delete>

3.update标签
具体属性与insert标签一致

<update id="updateUser" parameterType="com.mybatis.VO.UserVO">      update user_table set userName=#{userName},userAge=#{userAge},userPhone=#{userPhone} where userId=#{id}  </update> 

4.select标签
select标签属性
id:在命名空间中唯一的标识符,可以被用来引用这条语句。
parameterType:将会传入这条语句的参数类的完全限定名或别名。
resultType:从这条语句中返回的期望类型的类的完全限定名或别名。注意如果是集合情形,那应该是集合可以包含的类型,而不能是集合本身。使用 resultType 或resultMap,但不能同时使用。
resultMap:外部 resultMap 的命名引用。结果集的映射是 MyBatis 最强大的特性,对其有一个很好的理解的话,许多复杂映射的情形都能迎刃而解。使用 resultMap 或resultType,但不能同时使用。
flushCache:将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:false。
useCache:将其设置为 true,将会导致本条语句的结果被二级缓存,默认值:对 select 元素为 true。
timeout:这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)。
fetchSize:这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为 unset(依赖驱动)。
statementType:STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。
resultSets:这个设置仅对多结果集的情况适用,它将列出语句执行后返回的结果集并每个结果集给一个名称,名称是逗号分隔的。

 <select id="selectUserById" parameterType="int" resultMap="UserVO">          select <include refid="column" /> from user_table <include refid="where"/> </select> 

<include refid="column" />:引用sql片段可以减少代码冗余

<sql id="columns">       userId, userName, userAge,userPhone</sql>

<include refid="where"/>:引用sql片段可以减少代码冗余

<sql id="where"><where><if test="userId !=null and userId !=''">AND A.userId = #{userId,jdbcType=CHAR}</if></where></sql>

耐心之树,结黄金之果。

1 0