Mybatis学习-ResultMap

在Mybatis的配置中,标签有非常多的属性,其中ResultMap的标签尤其令我头疼,故写一篇随笔来简单解释一下ResultMap。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper
 3     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5     <mapper namespace="com.how2java.pojo">
 6         <resultMap type="Category" id="categoryBean">
 7             <id column="cid" property="id" />
 8             <result column="cname" property="name" />
 9      
10             <!-- 一对多的关系 -->
11             <!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
12             <collection property="products" ofType="Product">
13                 <id column="pid" property="id" />
14                 <result column="pname" property="name" />
15                 <result column="price" property="price" />
16             </collection>
17         </resultMap>
18      
19         <!-- 关联查询分类和产品表 -->
20         <select id="listCategory" resultMap="categoryBean">
21             select c.*, p.*, c.id 'cid', p.id 'pid', c.name 'cname', p.name 'pname' from category_ c left join product_ p on c.id = p.cid
22         </select>    
23     </mapper>

上面对Category的配置中,可先看到select标签,id属性用于后台进行调用:

 1 public static void main(String[] args) throws IOException {
 2         String resource = "mybatis-config.xml";
 3         InputStream inputStream = Resources.getResourceAsStream(resource);
 4         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 5         SqlSession session=sqlSessionFactory.openSession();
 6          
 7         List<Category> cs=session.selectList("listCategory");
 8         for (Category c : cs) {
 9             System.out.println(c.getName());
10         }
11          
12     }
View Code

而其中的resultmap属性则为重点,其实select标签有两种result属性:

resultType:从这条语句要返回的期望类型的类的完全限定名或别名(这里注意下集合类型,应该是集合可以包含的类型,不能是集合本身),重要:使用resultType或resultMap,但不能同时使用。
resultMap:命名引用外部的resultMap,其名称要和外部的resultMap元素的ID名称一致,用于映射其结果到实体类指定对象中。

而这两种属性的使用场景如何呢?

一般,当我们需要查询一整张表时,我们我就会用到resultType,这时mybatis会自动创建一个resultMap,直接映射到对应的JavaBean之上。

而要用到resultMap时,则需要写出如上所示的resultMap标签。

selet标签还有一个属性,parameterType属性,即参数类型属性,该属性用于表明sql中传递参数的类型。

parameterType属性现在可以使用的有两种:

1.基本数据类型:如int,String等,作为基本数据类型只能传入一个,通过#{参数名}获取。

2.复杂数据类型:包括Java实体类、Map,通过#{属性名}或#{Map的KeyName}获取。

上面两种情况如下所示

<delete id="deleteCategory" parameterType="Category" >
            delete from category_ where id= #{id}   
</delete>
         
<select id="getCategory" parameterType="_int" resultType="Category">
            select * from   category_  where id= #{id}    
</select>

对于resultMap标签,它具有id和type属性,id属性代表其表示,type属性则表示其映射的类。

其还具备两个子标签:id:表示主键,作为唯一标识。result:表示属性。

property:实体类中定义对象的名称,用于映射数据库列的字段与属性。

column:数据库中的字段名,和property对应。

从其他博客中看到一张图片能图较清晰的明了这其中的关系。

来源:https://blog.csdn.net/u013364878/article/details/78658232?utm_source=blogxgwz0

原文地址:https://www.cnblogs.com/huqingfeng/p/12526901.html