Mybatis Mapper XML

作者:範宗雲 来源:原创 发布时间:2015-04-25 归档:mybatis

环境 : JDK 7 Mybatis 3.2.7 Maven 3 Junit 4.11 Spring 4.1.5 Eclipse Luna
namespace
            <mapper namespace="org.lychie.mapper.ArticleMapper">

            </mapper>
          
mybatis 的前身是 ibatis, 在 ibatis 中 namespace 是可选的。在 mybatis 中, namespace 是必须项, 它用于将当前的 XML 映射文件与指定的 Mapper 接口绑定起来。namespace 的值为需要绑定的 Mapper 接口的完全限定名。
select
            <select id="queryById" parameterType="int" resultType="Article">
              SELECT * FROM ARTICLE WHERE ID = #{ID}
            </select>
          
映射查询语句。参数语法参考 :Mybatis SQL Parameters
parameterType
指定 SQL 参数的类型。int 是 mybatis 内建的类型别名, 映射到的类型是 Integer。具体见下面的表格。
resultType
指定 SQL 查询结果的数据类型。( 此处的 Article 是类型别名, 如果类没有定义别名, 那就需使用类的完全限定名 org.lychie.model.Article )。如果查询结果是一个 List 集合, 应指定集合的元素的类型。
id
在命名空间内必须保证其唯一性, 用于代表这条 SQL 语句。在 Mapper 接口中声明与此 id 一致的方法, 就能将 SQL 绑定到此方法中, Mapper 接口不需要手工编写实现类, 你只需声明方法, 剩下的事情就都交给 mybatis 来做了。
org.lychie.mapper.ArticleMapper
    			public interface ArticleMapper {
    			
    				Article queryById(int id);
    				
    			}          
          
mybatis 内建别名映射的类型

别 名 映 射 的 类 型
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

insert
            <insert id="save" parameterType="Article">
              INSERT INTO ARTICLE(TITLE, AUTHOR, CONTENT, CREATETIME) 
                VALUES(#{title}, #{author}, #{content}, now())
            </insert>
          
映射插入语句。参数语法参考 :Mybatis SQL Parameters
            public interface ArticleMapper {
			  
			  Integer save(Article article);
			  
			}
          
注意这里返回的不是插入的记录的主键, 而是成功插入记录的条数。
update
            <update id="update" parameterType="Article">
              UPDATE ARTICLE SET TITLE = #{title}, CONTENT = #{content}, CREATETIME = now()
                WHERE ID = #{id}
            </update>
          
映射更新语句。参数语法参考 :Mybatis SQL Parameters
			public interface ArticleMapper {
				
				Integer update(Article article);
				
			}
          
返回值为成功更新记录的条数。
delete
            <delete id="delete" parameterType="Article">
              DELETE FROM ARTICLE WHERE ID = #{id}
            </delete>
            
            <delete id="deleteById" parameterType="int">
              DELETE FROM ARTICLE WHERE ID = #{ID}
            </delete>
          
映射删除语句。参数语法参考 :Mybatis SQL Parameters
          public interface ArticleMapper {
            
            Integer deleteById(int id);
            
            Integer delete(Article article);
            
          }
          
返回值为成功删除记录的条数。