zoukankan      html  css  js  c++  java
  • MyBatis(三)MyBatis resultMap和注解

    MyBatis 目录

    MyBatis resultMap元素

    resultMap 是 MyBatis 中最复杂的元素,主要用于解决实体类属性名与数据库表中字段名不一致的情况,可以将查询结果映射成实体对象。下面我们先从最简单的功能开始介绍。

    resultMap元素的构成

    resultMap 元素还可以包含以下子元素,代码如下。

    <resultMap id="" type="">
        <constructor><!-- 类再实例化时用来注入结果到构造方法 -->
            <idArg/><!-- ID参数,结果为ID -->
            <arg/><!-- 注入到构造方法的一个普通结果 --> 
        </constructor>
        <id/><!-- 用于表示哪个列是主键 -->
        <result/><!-- 注入到字段或JavaBean属性的普通结果 -->
        <association property=""/><!-- 用于一对一关联 -->
        <collection property=""/><!-- 用于一对多、多对多关联 -->
        <discriminator javaType=""><!-- 使用结果值来决定使用哪个结果映射 -->
            <case value=""/><!-- 基于某些值的结果映射 -->
        </discriminator>
    </resultMap>
    

    其中:

    • 元素的 type 属性表示需要的 POJO,id 属性是 resultMap 的唯一标识。
    • 子元素 用于配置构造方法。当一个 POJO 没有无参数构造方法时使用。
    • 子元素 用于表示哪个列是主键。允许多个主键,多个主键称为联合主键。
    • 子元素 用于表示 POJO 和 SQL 列名的映射关系。
    • 子元素 用在级联的情况下。关于级联的问题比较复杂,在《MyBatis一对一关联查询》和《MyBatis一对多关联查询》一节详细讲解。

    id 和 result 元素都有以下属性。

    元素 说明
    property 映射到列结果的字段或属性。如果 POJO 的属性和 SQL 列名(column元素)是相同的,那么 MyBatis 就会映射到 POJO 上
    column 对应 SQL 列
    javaType 配置 Java 类型。可以是特定的类完全限定名或 MyBatis 上下文的别名
    jdbcType 配置数据库类型。这是 JDBC 类型,MyBatis 已经为我们做了限定,基本支持所有常用数据库类型
    typeHandler 类型处理器。允许你用特定的处理器来覆盖 MyBatis 默认的处理器。需要指定 jdbcType 和 javaType 相互转化的规则

    一条 SQL 查询语句执行后会返回结果集,结果集有两种存储方式,即使用 Map 存储和使用 POJO 存储。

    使用Map存储结果集

    任何 select 语句都可以使用 Map 存储,代码如下。

    <!-- 查询所有信息存到Map中 -->
    <select id="selectAllBlog" resultType="map">
        select * from blog
    </select>
    

    使用POJO存储结果集

    ​ 因为 MyBatis 提供了自动映射,所以使用 POJO 存储结果集是最常用的方式。但有时候需要更加复杂的映射或级联,这时就需要使用 select 元素的resultMap属性配置映射集合。

     <resultMap id="blogMap" type="org.mybatis.example.Blog">
            <!-- property 是 org.mybatis.example.Blog 类中的属性 -->
            <!-- column是查询结果的列名,可以来自不同的表 -->
            <id property="id" column="id" />
            <result property="blogTitle" column="blog_title" />
            <result property="desc" column="desc" />
        </resultMap>
    

    resultMap 元素的属性 id 代表这个 resultMap 的标识,type 标识需要映射的 POJO。我们可以使用MyBatis定义好的类的别名或自定义类的全限定名。

    这里使用 property 元素指定 Blog的属性名称 blogTitle,column 表示数据库中 blog表的 SQL 列名 blog_title,将 POJO 和 SQL 的查询结果一 一对应。

    Blog类中的blogTitle属性和blog表中的blog_title列对应

    <select id="selectAllBlog" resultMap="blogMap">
        select id,blog_title,desc from blog
    </select>
    

    resultType和resultMap的区别

    MyBatis 的每一个查询映射的返回类型都是 resultMap,只是当我们提供的返回类型是 resultType 时,MyBatis 会自动把对应的值赋给 resultType 所指定对象的属性,而当我们提供的返回类型是 resultMap 时,MyBatis 会将数据库中的列数据复制到对象的相应属性上,可用于复制查询。

    需要注意的是,resultMapresultType 不能同时使用。

    MyBatis注解(3种类型)

    为了简化 XML 的配置,MyBatis 提供了注解。

    1. SQL 语句映射

    @Insert:实现新增功能

    @Insert("insert into user(id,name) values(#{id},#{name})")
    public int insert(User user);
    

    @Select:实现查询功能

    @Select("Select * from user")
    @Results({
        @Result(id = true, column = "id", property = "id"),
        @Result(column = "name", property = "name"),
        @Result(column = "sex", property = "sex"),
        @Result(column = "age", property = "age")
    })
    List<User> queryAllUser();
    

    @SelectKey:插入后,获取id的值

    以 MySQL 为例,MySQL 在插入一条数据后,使用select last_insert_id()可以获取到自增 id 的值。

    @Insert("insert into user(id,name) values(#{id},#{name})")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", keyColumn = "id", resultType = int,before = false)
    public int insert(User user);
    

    @SelectKey 各个属性含义如下。

    • statement:表示要运行的 SQL 语句;
    • keyProperty:可选项,表示将查询结果赋值给代码中的哪个对象;
    • keyColumn:可选项,表示将查询结果赋值给数据表中的哪一列;
    • resultType:指定 SQL 语句的返回值;
    • before:默认值为 true,在执行插入语句之前,执行 select last_insert_id()。值为 flase,则在执行插入语句之后,执行 select last_insert_id()

    @Insert:实现插入功能

    @Insert("insert into user(name,sex,age) values(#{name},#{sex},#{age}")
    int saveUser(User user);
    

    5)@Update:实现更新功能

    @Update("update user set name= #{name},sex = #{sex},age =#{age} where id = #{id}")
    void updateUserById(User user);
    

    6)@Delete:实现删除功能

    @Delete("delete from  user  where id =#{id}")
    void deleteById(Integer id);
    

    7)@Param:映射多个参数

    @Param 用于在 Mapper 接口中映射多个参数。

    int saveUser(@Param(value="user") User user,@Param("name") String name,@Param("age") Int age);
    

    @Param 中的 value 属性可省略,用于指定参数的别名。

    2. 结果集映射

    @Result、@Results、@ResultMap 是结果集映射的三大注解。

    声明结果集映射关系代码:

    Select({"select id, name, class_id from student"})
    @Results(id="studentMap", value={
        @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
        @Result(column="class_id ", property="classId", jdbcType=JdbcType.INTEGER)
    })
    List<Student> selectAll();
    

    下面为 @Results 各个属性的含义。

    • id:表示当前结果集声明的唯一标识;
    • value:表示结果集映射关系;
    • @Result:代表一个字段的映射关系。其中,column 指定数据库字段的名称,property 指定实体类属性的名称,jdbcType 数据库字段类型,id 为 true 表示主键,默认 false。

    可使用 @ResultMap 来引用映射结果集,其中 value 可省略。

    @Select({"select id, name, class_id from student where id = #{id}"})
    @ResultMap(value="studentMap")
    Student selectById(Integer id);
    

    这样不需要每次声明结果集映射时都复制冗余代码,简化开发,提高了代码的复用性。

    3. 关系映射

    @one:用于一对一关系映射

    @Select("select * from student") 
    @Results({ 
        @Result(id=true,property="id",column="id"), 
        @Result(property="name",column="name"), 
        @Result(property="age",column="age"), 
        @Result(property="address",column="address_id",one=@One(select="net.biancheng.mapper.AddressMapper.getAddress")) 
    }) 
    public List<Student> getAllStudents();  
    

    @many:用于一对多关系映射

    @Select("select * from t_class where id=#{id}") 
    @Results({ 
        @Result(id=true,column="id",property="id"), 
        @Result(column="class_name",property="className"), 
        @Result(property="students", column="id", many=@Many(select="net.biancheng.mapper.StudentMapper.getStudentsByClassId")) 
        }) 
    public Class getClass(int id); 
    
  • 相关阅读:
    Spring实现AOP的4种方式(转)
    【转】一个不错的eclipse反编译插件
    spring配置事务
    使用XFire+Spring构建Web Service(一)——helloWorld篇
    WebService到底是什么?(转)
    ContextLoaderListener作用详解(转)
    SVN检出资源文件
    ExtJS4.2学习(21)动态菜单与表格数据展示操作总结篇2
    WP8_当滚动到滚动条的70%时,自动加载数据效果实现
    WP8__从windowsphone app store 中根据app id获取应用的相关信息(下载网址及图片id等)
  • 原文地址:https://www.cnblogs.com/qs315/p/15702916.html
Copyright © 2011-2022 走看看