MyBatis使用大全(5)------映射器类

来源:互联网 发布:微信炸群软件 编辑:程序博客网 时间:2024/06/08 08:18

MyBatis的SqlSession中包括方法,映射sql等等。

SqlSession中包括了很多方法,简单截了个图如下:

包括了增删改查等方法以及方法的多种重载形式等等。

直接使用SqlSession的方法形式如下:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. User user = session.selectOne("com.lanhuigu.mybatis.map.UserMainMapper.queryUserMainById"1);  
  2. 或  
  3. <pre name="code" class="java">User user = session.selectOne("queryUserMainById"1);  
根据字符串去XML中寻找元素select下id为queryUserMainById的方法,并传入参数1,执行查询,返回User对象。

直接使用SqlSession方法功能也很强大,但是会使得整个系统代码没有类型安全,也很繁琐。

所以,一个更通用的方式来执行映射语句是使用映射器类。

一个映射器类就是一个简单的接口,其中的方法定义匹配于 SqlSession 方法。比如:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. package com.lanhuigu.mybatis.map;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import org.apache.ibatis.annotations.Delete;  
  7. import org.apache.ibatis.annotations.Insert;  
  8. import org.apache.ibatis.annotations.Options;  
  9. import org.apache.ibatis.annotations.Param;  
  10. import org.apache.ibatis.annotations.Select;  
  11. import org.apache.ibatis.annotations.Update;  
  12.   
  13. import com.lanhuigu.mybatis.entity.User;  
  14.   
  15. public interface UserMainMapper {  
  16.       
  17.     /** 
  18.      * 查询用户对象--返回User对象 
  19.      */  
  20.     // (User)selectOne("queryUserMainById",1);  
  21.     public User queryUserMainById(int id);  
  22.   
  23. }  
*******匹配情况:

总之, 每个映射器方法签名应该匹配相关联的 SqlSession 方法, 也就是说,

如果你用的是xml,必须与xml中select下的id一样,但是这里没有字符串参数 ID。

相反,方法名必须匹配映射语句的 ID。


******返回类型:

返回类型为自己期望的类型。支持多种返回值类型,例如:原生类型,Map,POJO 和 JavaBean。


******是否需要实现映射器类接口:

映射器接口不需要去实现任何接口或扩展任何类。

只要方法前面可以被用来唯一标识对应的映射语句就可以了。

映射器接口可以扩展其他接口。当使用 XML 来构建映射器接口时要保证在合适的命名空间中有语句。

而且, 唯一的限制就是你不能在两个继承关系的接口中有相同的方法签名 (这也是不好的想法)。

你可以传递多个参数给一个映射器方法。

如果你这样做了, 默认情况下它们将会以它们在参数列表中的位置来命名,比如:#{param1},#{param2}等。

如果你想改变参数的名称(只在多参数情况下) ,那么你可以在参数上使用@Param(“paramName”)注解。

你也可以给方法传递一个 RowBounds 实例来限制查询结果。


总结:

使用映射器类可以对持久层管理更规范,使用快捷,统一编码形式,方便维护。


******映射器类注解:

说到映射器类,在前面也接触过注解使用,说到映射器类,还需要了解映射器注解。

MyBatis一开始设计使用的是通过XML做驱动的框架,所以,注解有其局限性。

比如,MyBatis的动态sql使用,在xml中可以使用各种元素玩转动态sql拼接,

但是使用注解确没有这种功效。我们有时候需要使用注解,看看注解都有哪些可用:

自己列表格太费劲,水平有限,很难列完整,从网上找了一个,以后就当字典查了。

注解目标相对应的 XML描述@CacheNamespace<cache>为给定的命名空间 (比如类) 配置缓存。属性:implemetation,eviction, flushInterval,size 和 readWrite。@CacheNamespaceRef<cacheRef>参照另外一个命名空间的缓存来使用。属性:value,应该是一个名空间的字符串值(也就是类的完全限定名) 。@ConstructorArgsMethod<constructor>收集一组结果传递给一个劫夺对象的构造方法。属性:value,是形式参数的数组。@Arg方法
  • <arg>
  • <idArg>
单 独 的 构 造 方 法 参 数 , 是 ConstructorArgs 集合的一部分。属性: id,column,javaType,typeHandler。 id 属性是布尔值, 来标识用于比较的属性,和<idArg>XML 元素相似。@TypeDiscriminator方法<discriminator>一组实例值被用来决定结果映射的表现。属性: column, javaType, jdbcType, typeHandler,cases。cases 属性就是实例的数组。@Case方法<case>单独实例的值和它对应的映射。属性: value,type,results。Results 属性是结果数组,因此这个注解和实际的 ResultMap 很相似,由下面的 Results 注解指定。@Results方法<resultMap>结果映射的列表, 包含了一个特别结果列如何被映射到属性或字段的详情。属 性:value, id。value 属性是 Result 注解的数组。 The id attribute is the name of the result mapping.@Result方法
  • <result>
  • <id>
在列和属性或字段之间的单独结果映射。属 性:id,column, property, javaType ,jdbcType ,type Handler, one,many。id 属性是一个布尔值,表示了应该被用于比较(和在 XML 映射中的<id>相似)的属性。one 属性是单独 的 联 系, 和 <association> 相 似 , 而 many 属 性 是 对 集 合 而 言 的 , 和 <collection>相似。它们这样命名是为了避免名称冲突。@One方法<association>复杂类型的单独属性值映射。属性: select,已映射语句(也就是映射器方法)的完全限定名,它可以加载合适类型的实例。注意:联合映射在注解 API 中是不支持的。这是因为 Java 注解的限制,不允许循环引用。fetchType, which supersedes the global configuration parameterlazyLoadingEnabled for this mapping.@Many方法<collection>A mapping to a collection property of a complex type. Attributes: select, which is the fully qualified name of a mapped statement (i.e. mapper method) that can load a collection of instances of the appropriate types,fetchType, which supersedes the global configuration parameter lazyLoadingEnabled for this mapping.NOTE You will notice that join mapping is not supported via the Annotations API. This is due to the limitation in Java Annotations that does not allow for circular references.@MapKey方法 复 杂 类 型 的 集合 属 性 映射 。 属 性 : select,是映射语句(也就是映射器方法)的完全限定名,它可以加载合适类型的一组实例。注意:联合映射在 Java 注解中是不支持的。这是因为 Java 注解的限制,不允许循环引用。@Options方法映射语句的属性这个注解提供访问交换和配置选项的宽广范围, 它们通常在映射语句上作为属性出现。而不是将每条语句注解变复杂,Options 注解提供连贯清晰的方式来访问它们。属性:useCache=true , flushCache=FlushCachePolicy.DEFAULT , resultSetType=FORWARD_ONLY , statementType=PREPARED , fetchSize=-1 , , timeout=-1 useGeneratedKeys=false , keyProperty=”id” , keyColumn=”” , resultSets=””。理解 Java 注解是很重要的,因为没有办法来指定“null” 作为值。因此,一旦你使用了 Options 注解,语句就受所有默认值的支配。要注意什么样的默认值来避免不期望的行为。
  • @Insert
  • @Update
  • @Delete
  • @Select
方法
  • <insert>
  • <update>
  • <delete>
  • <select>
这些注解中的每一个代表了执行的真实 SQL。它们每一个都使用字符串数组 (或单独的字符串)。如果传递的是字符串数组, 它们由每个分隔它们的单独空间串联起来。这就当用 Java 代码构建 SQL 时避免了“丢失空间”的问题。然而,如果你喜欢,也欢迎你串联单独的字符串。属性:value,这是字符串数组用来组成单独的 SQL 语句。
  • @InsertProvider
  • @UpdateProvider
  • @DeleteProvider
  • @SelectProvider
方法
  • <insert>
  • <update>
  • <delete>
  • <select>
这些可选的 SQL 注解允许你指定一个类名和一个方法在执行时来返回运行允许创建动态 的 SQL。基于执行的映射语句, MyBatis 会实例化这个类,然后执行由 provider 指定的方法. 该方法可以有选择地接受参数对象.(In MyBatis 3.4 or later, it's allow multiple parameters) 属性: type,method。type 属性是类。method 属性是方法名。注意: 这节之后是对 类的讨论,它可以帮助你以干净,容于阅读的方式来构建动态 SQL。@ParamParameterN/A如果你的映射器的方法需要多个参数, 这个注解可以被应用于映射器的方法参数来给每个参数一个名字。否则,多参数将会以它们的顺序位置来被命名 (不包括任何 RowBounds 参数) 比如。 #{param1} , #{param2} 等 , 这 是 默 认 的 。 使 用 @Param(“person”),参数应该被命名为 #{person}。@SelectKeyMethod<selectKey>This annotation duplicates the <selectKey> functionality for methods annotated with@Insert,@InsertProvider, @Update or @UpdateProvider. It is ignored for other methods. If you specify a@SelectKey annotation, then MyBatis will ignore any generated key properties set via the@Options annotation, or configuration properties. Attributes: statement an array of strings which is the SQL statement to execute,keyProperty which is the property of the parameter object that will be updated with the new value, before which must be eithertrue orfalse to denote if the SQL statement should be executed before or after the insert,resultType which is the Java type of thekeyProperty, and statementType=PREPARED.@ResultMapMethodN/AThis annotation is used to provide the id of a <resultMap> element in an XML mapper to a@Select or@SelectProvider annotation. This allows annotated selects to reuse resultmaps that are defined in XML. This annotation will override any@Results or@ConstructorArgs annotation if both are specified on an annotated select.@ResultTypeMethodN/AThis annotation is used when using a result handler. In that case, the return type is void so MyBatis must have a way to determine the type of object to construct for each row. If there is an XML result map, use the @ResultMap annotation. If the result type is specified in XML on the <select> element, then no other annotation is necessary. In other cases, use this annotation. For example, if a @Select annotated method will use a result handler, the return type must be void and this annotation (or @ResultMap) is required. This annotation is ignored unless the method return type is void.@FlushMethodN/AIf this annotation is used, it can be called the SqlSession#flushStatements() via method defined at a Mapper interface.(MyBatis 3.3 or above)

列举一个XML和注解使用,返回一条,或多条数据的实例:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. package com.lanhuigu.mybatis.map;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import org.apache.ibatis.annotations.Delete;  
  7. import org.apache.ibatis.annotations.Insert;  
  8. import org.apache.ibatis.annotations.Options;  
  9. import org.apache.ibatis.annotations.Param;  
  10. import org.apache.ibatis.annotations.Select;  
  11. import org.apache.ibatis.annotations.Update;  
  12.   
  13. import com.lanhuigu.mybatis.entity.User;  
  14.   
  15. public interface UserMainMapper {  
  16.     //=======================XML版=======================  
  17.     /** 
  18.      * 查询用户对象--返回User对象 
  19.      */  
  20.     // (User)selectOne("queryUserMainById",1);  
  21.     public User queryUserMainById(int id);  
  22.     /** 
  23.      * 查询用户对象--返回多个--List<User> 
  24.      */  
  25.     public List<User> queryUserMainList();  
  26.     /** 
  27.      * 查询用户对象--返回map 
  28.      */  
  29.     public Map<String,Object> queryUserMainResultMap(int id);  
  30.     /** 
  31.      * 查询用户对象--返回多个--List<Map<String,Object>> 
  32.      */  
  33.     public List<Map<String,Object>> queryUserMainResultListMap();  
  34.     /** 
  35.      * 插入用户对象 
  36.      */  
  37.     public int insertUser(User user);  
  38.     /** 
  39.      * 更新用户对象 
  40.      */  
  41.     public int updateUser(User user);  
  42.     /** 
  43.      * 删除用户对象 
  44.      */  
  45.     public int deleteUser(int id);  
  46.       
  47.     //=======================注解版==========================  
  48.     /** 
  49.      * 查询用户对象--返回User对象 
  50.      */  
  51.     @Select(" select f_id id,f_username username,f_age age from t_user_main where f_id = #{id} ")  
  52.     @Options(flushCache=true)  
  53.     public User queryUserMainByIdNew(@Param("id"int id);  
  54.     /** 
  55.      * 查询用户对象--返回多个--List<User> 
  56.      */  
  57.     @Select("select f_id id,f_username username,f_age age from t_user_main ")  
  58.     @Options(flushCache=true)  
  59.     public List<User> queryUserMainListNew();  
  60.     /** 
  61.      * 查询用户对象--返回map 
  62.      */  
  63.     @Select("select f_id id,f_username username,f_age age from t_user_main where f_id = #{id}")  
  64.     @Options(flushCache=true)  
  65.     public Map<String,Object> queryUserMainResultMapNew(@Param("id"int id);  
  66.     /** 
  67.      * 查询用户对象--返回多个--List<Map<String,Object>> 
  68.      */  
  69.     @Select("select f_id id,f_username username,f_age age from t_user_main")  
  70.     @Options(flushCache=true)  
  71.     public List<Map<String,Object>> queryUserMainResultListMapNew();  
  72.     /** 
  73.      * 插入用户对象 
  74.      */  
  75.     @Insert("insert into t_user_main (f_id,f_username,f_age) "  
  76.             + " values(#{id},#{username},#{age}) ")  
  77.     @Options(useGeneratedKeys=false)  
  78.     public int insertUserNew(User user);  
  79.     /** 
  80.      * 更新用户对象 
  81.      */  
  82.     @Update("update t_user_main set f_username=#{username},f_age=#{age} "  
  83.             + " where f_id=#{id} ")  
  84.     public int updateUserNew(User user);  
  85.     /** 
  86.      * 删除用户对象 
  87.      */  
  88.     @Delete("delete from t_user_main where f_id=#{id}")  
  89.     @Options(flushCache=true)  
  90.     public int deleteUserNew(@Param("id"int id);  

0 0
原创粉丝点击