Mybatis 主流经典面试题·吊打面试官

目录

Mybatis 工作原理详解

1、Mybaits的优缺点?

2、#{}和${}的区别是什么? 

3、通常一个mapper.xml文件,都会对应一个Dao接口,这个Dao接口的工作原理是什么?Dao接口里的方法,参数不同时,方法能重载吗? 

4、Mybatis的Xml映射文件中,不同的Xml映射文件,id是否可以重复?

5、Mybatis是如何进行分页的?分页插件的原理是什么?

6、Mybatis是否支持延迟加载?如果支持,它的实现原理是什么?

7、Mybatis的一级、二级缓存:

8、Mybatis是如何将sql执行结果封装为目标对象并返回的?都有哪些映射形式?

9、Mybatis动态sql有什么用?执行原理?有哪些动态sql?

10、Xml映射文件中,除了常见的select|insert|updae|delete标签外,还有哪些标签?

11、使用MyBatis的mapper接口调用时有哪些要求?

12、模糊查询like语句该怎么写? 

13、当实体类中的属性名和表中的字段名不一样 ,怎么办 ?

14、如何获取自动生成的(主)键值?

15、在mapper中如何传递多个参数?

16、一对一、一对多的关联查询 ? 

17、MyBatis实现一对一有几种方式?具体怎么操作的?

18、MyBatis实现一对多有几种方式,怎么操作的?

19、Mapper编写有哪几种方式?

20、什么是MyBatis的接口绑定?有哪些实现方式? 


Mybatis 工作原理详解

建议先了解其工作原理再度刷题,效果更好

(64条消息) Mybatis 工作原理详解_mybatis原理_九块六的博客-CSDN博客

1、Mybaits的优缺点?

(1)优点:

① 与JDBC相比,减少了50%以上的代码量,消除了JDBC大量冗余的代码,不需要手动开关连接;

② 基于SQL语句编程,相当灵活,不会对应用程序或者数据库的现有设计造成任何影响,SQL写在XML里,解除sql与程序代码的耦合,便于统一管理;提供XML标签,支持编写动态SQL语句,并可重用。

③ 很好的与各种数据库兼容(因为MyBatis使用JDBC来连接数据库,所以只要JDBC支持的数据库MyBatis都支持)。

④ 能够与Spring很好的集成;

⑤ 提供映射标签,支持对象与数据库的ORM字段关系映射;提供对象关系映射标签,支持对象关系组件维护

(2)缺点:

① SQL语句的编写工作量较大,尤其当字段多、关联表多时,对开发人员编写SQL语句的功底有一定要求。

② SQL语句依赖于数据库,导致数据库移植性差,不能随意更换数据库

2、#{}和${}的区别是什么? 

${}是字符串替换,#{}是预处理;使用#{}可以有效的防止SQL注入,提高系统安全性。

Mybatis在处理${}时,就是把${}直接替换成变量的值。而Mybatis在处理#{}时,会对sql语句进行预处理,将sql中的#{}全部替换为?号,然后调用PreparedStatement的set方法来给“?”赋值;

相同的入参 id = 3;drop table user;

#{} 的SQL预编译结果:

        select name from usre where id = "3;drop table user;"
${} 的结果:

        select name from user where id = 3;drop table user ;

${} 形成了两个SQL语句,造成了SQL注入 

补充:什么时候必须需要使用${}?

 当动态传入sql 当中的数据库表名称的时候,必须使用${},因为#{}的编译会给加上' ',select * from 'user':导致无法识别这个是表名的

3、通常一个mapper.xml文件,都会对应一个Dao接口,这个Dao接口的工作原理是什么?Dao接口里的方法,参数不同时,方法能重载吗? 

Mapper 接口的工作原理是JDK动态代理,Mybatis运行时会使用JDK动态代理为Mapper接口生成代理对象 MappedProxy,代理对象会拦截接口方法,根据类的全限定名+方法名,唯一定位到一个MapperStatement并调用执行器执行所代表的sql,然后将sql执行结果返回。

Mapper接口里的方法,是不能重载的,因为是使用 全限名+方法名 的保存和寻找策略

(1)Dao接口,就是Mapper接口。
(2)接口的全限名,就是映射文件中的namespace的值;
(3)接口的方法名,就是映射文件中Mapper的Statement的id值;
(4)接口方法内的参数,就是传递给sql的参数。
        当调用接口方法时,通过 “接口全限名+方法名”拼接字符串作为key值,可唯一定位一个MapperStatement,因为在Mybatis中,每一个SQL标签,都会被解析为一个MapperStatement对象。

举例:com.mybatis3.mappers.StudentDao.findStudentById,可以唯一找到namespace为com.mybatis3.mappers.StudentDao下面 id 为 findStudentById 的 MapperStatement

使用要求:

  •  Mapper接口方法名和mapper.xml中定义的每个sql的id相同;
  •  Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同;
  •  Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同;
  •  Mapper.xml文件中的namespace即是mapper接口的类路径

4、Mybatis的Xml映射文件中,不同的Xml映射文件,id是否可以重复?

不同的Xml映射文件,如果配置了namespace,那么id可以重复;如果没有配置namespace,那么id不能重复;原因就是namespace+id是作为Map的key使用的,如果没有namespace,就剩下id,那么,id重复会导致数据互相覆盖。有了namespace,自然id就可以重复,namespace不同,namespace+id自然也就不同

备注:在旧版本的Mybatis中,namespace是可选的,不过新版本的namespace已经是必填项了。

 5、Mybatis是如何进行分页的?分页插件的原理是什么?

        Mybatis使用RowBounds对象进行分页,它是针对ResultSet结果集执行的内存分页,而非物理分页。可以在sql内直接书写带有物理分页的参数来完成物理分页功能,也可以使用分页插件来完成物理分页。

       分页插件的基本原理是使用Mybatis提供的插件接口,实现自定义插件,在插件的拦截方法内拦截待执行的sql,然后重写sql,根据dialect方言,添加对应的物理分页语句和物理分页参数。


6、Mybatis是否支持延迟加载?如果支持,它的实现原理是什么?

 Mybatis仅支持association关联对象和collection关联集合对象的延迟加载,association指的就是一对一,collection指的就是一对多查询。在Mybatis配置文件中,可以配置是否启用延迟加载lazyLoadingEnabled=true|false。

        延迟加载的基本原理是,使用CGLIB创建目标对象的代理对象,当调用目标方法时,进入拦截器方法,比如调用a.getB().getName(),拦截器invoke()方法发现a.getB()是null值,那么就会单独发送事先保存好的查询关联B对象的sql,把B查询上来,然后调用a.setB(b),于是a的对象b属性就有值了,接着完成a.getB().getName()方法的调用。

        当然了,不光是Mybatis,几乎所有的包括Hibernate,支持延迟加载的原理都是一样的。

7、Mybatis的一级、二级缓存:

(1)一级缓存: 基于 PerpetualCache 的 HashMap 本地缓存,其存储作用域为 Session,当 Session flush 或 close 之后,该 Session 中的所有 Cache 就将清空,默认打开一级缓存。

(2)二级缓存与一级缓存其机制相同,默认也是采用 PerpetualCache,HashMap 存储,不同在于其存储作用域为 Mapper(Namespace),并且可自定义存储源,如 Ehcache。默认不打开二级缓存,要开启二级缓存,使用二级缓存属性类需要实现Serializable序列化接口(可用来保存对象的状态),可在它的映射文件中配置 ;

(3)对于缓存数据更新机制,当某一个作用域(一级缓存 Session/二级缓存Namespaces)的进行了C/U/D 操作后,默认该作用域下所有 select 中的缓存将被 clear 掉并重新更新,如果开启了二级缓存,则只根据配置判断是否刷新。
 

8、Mybatis是如何将sql执行结果封装为目标对象并返回的?都有哪些映射形式?

第一种是使用标签,逐一定义数据库列名和对象属性名之间的映射关系。

第二种是使用sql列的别名功能,将列的别名书写为对象属性名。

有了列名与属性名的映射关系后,Mybatis通过反射创建对象,同时使用反射给对象的属性逐一赋值并返回,那些找不到映射关系的属性,是无法完成赋值的。

9、Mybatis动态sql有什么用?执行原理?有哪些动态sql?

Mybatis动态sql可以在Xml映射文件内,以标签的形式编写动态sql,执行原理是根据表达式的值 完成逻辑判断 并动态拼接sql的功能。

Mybatis提供了9种动态sql标签:trim | where | set | foreach | if | choose | when | otherwise | bind

choose,when,otherwise标签语句示例:

<!--
	有时不想应用到所有的条件语句,而只想从中择其一项,针对这种情况,Mybatis提供了choose元素
	它有点像java中的switch语句 
-->
<select id="queryUser" parameterType="map" resultType="user">
	  select * from usr
	  <where>
	      <choose>
	          <when test="id != null" >
	              id =#{id}
	          </when>
	          <when test="username != null" >
	              and username = #{username}
	          </when>
	          <otherwise>
	              and id= 4
	          </otherwise>
	      </choose>
	  </where>
</select>

where、if 标签语句示例: 

<!-- where 元素只会在至少有一个子元素的条件返回sql子句的情况下,才去插入"where" 子句-->
<select id="queryUser" parameterType="map" resultType="user">   
	  select * from usr  
		  <where>
			  <if test="id != null" >
			      id =#{id}
			  </if>
			  <if test="username != null" >
			      and username = #{username}
			  </if>
		  </where>
</select>

set 标签语句示例: 

<!--
	这里set元素会动态前置set关键字,同时也会删除掉无关的逗号
	因为用了条件语句之后很可能就会生成的sql后面留下这些逗号
 -->
<update id="updatePwd">
    update public."user"
    <set>

        <if test="name !=null">name=#{name},</if>
        <if test="pwd !=null">pwd=#{pwd},</if>
    </set>
    <where>
        <choose>
            <when test="id!=null">id=#{id}</when>
            <when test="name!=null">name=#{name}</when>
        </choose>
    </where>
</update>	

foreach 标签语句示例: 

<!--
第一步:迭代集合,获取对应的item,和外部的(),拼接形成('zhangsan')
第二步:在之前的基础上拼接上逗号分隔符('zhangsan'),
第三步:继续迭代并拼接逗号 ('zhangsan'),('lisi'),
第四步:继续迭代并拼接逗号 ('zhangsan'),('lisi'),('wangwu')
 -->
<foreach collection="list" item="item" separator=",">
	(#{item})
</foreach>


<!--
第一步:拼接open指定的开始字符 (
第二步:迭代集合,拼接对应的item, ('zhangsan'
第三步:拼接separator指定的分隔符 ('zhangsan',
第四步:迭代集合,拼接对应的item, ('zhangsan','lisi'
第五步:拼接separator指定的分隔符('zhangsan','lisi',
第六步:拼接close指定的闭合字符  ('zhangsan','lisi','wangwu') 
 -->
<foreach collection="list" item="item" open="(" separator="," close=")">
	#{item}
</foreach>

sql片段标签语句示例: 

<sql id="choose-when-id-name">
    <choose>
        <when test="id!=null">id=#{id}</when>
        <when test="name!=null">name=#{name}</when>
    </choose>
</sql>
<update id="updatePwd">
    update public."user"
    <set>
        <if test="name !=null">name=#{name},</if>
        <if test="pwd !=null">pwd=#{pwd},</if>
    </set>
    <where>
       <include refid="choose-when-id-name"></include>
    </where>
</update>

trim标签语句示例: 

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.harvey.java01.entity.User">
    select * from user
    <!-- <where>
            <if test="username != null">
               username=#{username}
            </if>

            <if test="sex != null">
               and sex=#{sex}
            </if>
        </where>  -->
    <trim prefix="where" prefixOverrides="and | or">
        <if test="username != null">
            and username=#{username}
        </if>
        <if test="sex != null">
            and sex=#{sex}
        </if>
    </trim>
</select>


<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.harvey.java01.entity.User">
    select * from user
    <!-- <where>
            <if test="username != null">
               username=#{username}
            </if>

            <if test="sex != null">
               and sex=#{sex}
            </if>
        </where>  -->
    <trim prefix="where" prefixOverrides="and | or">
        <if test="username != null">
            and username=#{username}
        </if>
        <if test="sex != null">
            and sex=#{sex}
        </if>
    </trim>
</select>

10、Xml映射文件中,除了常见的select|insert|updae|delete标签外,还有哪些标签?

还有:<resultMap>、<parameterMap>、<sql>、<include>、<selectKey>

加上动态sql的9个标签 trim | where | set | foreach | if | choose | when | otherwise | bind 等,

其中 <sql> 为sql片段标签,通过<include>标签引入sql片段,<selectKey>为不支持自增的主键生成策略标签

11、使用MyBatis的mapper接口调用时有哪些要求?

  •  Mapper接口方法名和mapper.xml中定义的每个sql的id相同;
  •  Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同;
  •  Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同;
  •  Mapper.xml文件中的namespace即是mapper接口的类路径

12、模糊查询like语句该怎么写? 

第1种:在Java代码中添加sql通配符。

    string wildcardname = “%smi%”;
    list<name> names = mapper.selectlike(wildcardname);
 
    <select id=”selectlike”>
     select * from foo where bar like #{value}
    </select>

第2种:在sql语句中拼接通配符,会引起sql注入

    string wildcardname = “smi”;
    list<name> names = mapper.selectlike(wildcardname);
 
    <select id=”selectlike”>
         select * from foo where bar like "%"${value}"%"
    </select>

13、当实体类中的属性名和表中的字段名不一样 ,怎么办 ?

第1种: 通过在查询的sql语句中定义字段名的别名

    <select id=”selectorder” parametertype=”int” resultetype=”me.gacl.domain.order”>
       select order_id id, order_no orderno ,order_price price form orders where order_id=#{id};
    </select>

第2种: 通过定义result标签映射字段名和实体类属性名的一一对应的关系

 <select id="getOrder" parameterType="int" resultMap="orderresultmap">
        select * from orders where order_id=#{id}
    </select>
 
   <resultMap type=”me.gacl.domain.order” id=”orderresultmap”>
        <!–用id属性来映射主键字段–>
        <id property=”id” column=”order_id”>
 
        <!–用result属性来映射非主键字段,property为实体类属性名,column为数据表中的属性–>
        <result property = “orderno” column =”order_no”/>
        <result property=”price” column=”order_price” />
    </reslutMap>

14、如何获取自动生成的(主)键值?

insert 方法总是返回一个int值 ,这个值代表的是插入的行数。 如果采用自增长策略,自动生成的键值在 insert 方法执行完后可以被设置到传入的参数对象中。usegeneratedkeys=”true” keyproperty=”id”

<insert id=”insertname” usegeneratedkeys=”true” keyproperty=”id”>
     insert into names (name) values (#{name})
</insert>
    name name = new name();
    name.setname(“fred”);
 
    int rows = mapper.insertname(name);
    // 完成后,id已经被设置到对象中
    system.out.println(“rows inserted = ” + rows);
    system.out.println(“generated key value = ” + name.getid());

15、在mapper中如何传递多个参数?

(1)第一种:
// DAO层的函数
Public UserselectUser(String name,String area);  
// 对应的xml,#{0}代表接收的是dao层中的第一个参数,#{1}代表dao层中第二参数,更多参数一致往后加即可。
<select id="selectUser"resultMap="BaseResultMap">  
    select *  fromuser_user_t   whereuser_name = #{0} anduser_area=#{1}  
</select>  
 
(2)第二种: 使用 @param 注解:
public interface usermapper {
   user selectuser(@param(“username”) string username,@param(“hashedpassword”) string hashedpassword);
}
然后,就可以在xml像下面这样使用(推荐封装为一个map,作为单个参数传递给mapper):
<select id=”selectuser” resulttype=”user”>
         select id, username, hashedpassword
         from some_table
         where username = #{username}
         and hashedpassword = #{hashedpassword}
</select>
 
(3)第三种:多个参数封装成map
public interface usermapper {
   user selectuser(Map<String, Object> map);
}
// 然后,就可以在xml像下面这样使用(推荐封装为一个map,作为单个参数传递给mapper):
<select id=”selectuser” resulttype=”map”>
         select id, username, hashedpassword
         from some_table
         where username = #{username}
         and hashedpassword = #{hashedpassword}
</select>

(4) 第四种:多个参数封装成实体对象
public interface usermapper {
   user selectuser(User user);
}
// 然后,就可以在xml像下面这样使用(推荐封装为一个map,作为单个参数传递给mapper):
<select id=”selectuser” resulttype=”com.entty.User”>
         select id, username, hashedpassword
         from some_table
         where username = #{username}
         and hashedpassword = #{hashedpassword}
</select>

16、一对一、一对多的关联查询 ? 

association  一对一关联查询;collection 一对多关联查询

<mapper namespace="com.lcb.mapping.userMapper">  
    <!--association  一对一关联查询 -->  
    <select id="getClass" parameterType="int" resultMap="ClassesResultMap">  
        select * from class c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id}  
    </select>  
 
    <resultMap type="com.lcb.user.Classes" id="ClassesResultMap">  
        <!-- 实体类的字段名和数据表的字段名映射 -->  
        <id property="id" column="c_id"/>  
        <result property="name" column="c_name"/>  
        <association property="teacher" javaType="com.lcb.user.Teacher">  
            <id property="id" column="t_id"/>  
            <result property="name" column="t_name"/>  
        </association>  
    </resultMap>  
 
 
    <!--collection  一对多关联查询 -->  
    <select id="getClass2" parameterType="int" resultMap="ClassesResultMap2">  
        select * from class c,teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=#{id}  
    </select>  
 
    <resultMap type="com.lcb.user.Classes" id="ClassesResultMap2">  
        <id property="id" column="c_id"/>  
        <result property="name" column="c_name"/>  
        <association property="teacher" javaType="com.lcb.user.Teacher">  
            <id property="id" column="t_id"/>  
            <result property="name" column="t_name"/>  
        </association>  
 
        <collection property="student" ofType="com.lcb.user.Student">  
            <id property="id" column="s_id"/>  
            <result property="name" column="s_name"/>  
        </collection>  
    </resultMap>  
</mapper> 

17、MyBatis实现一对一有几种方式?具体怎么操作的?

有联合查询和嵌套查询:

(1)联合查询是几个表联合查询,只查询一次, 通过在resultMap里面配置association节点配置一对一的类就可以完成;

(2)嵌套查询是先查一个表,根据这个表里面的结果的外键id,去再另外一个表里面查询数据,也是通过association配置,但另外一个表的查询通过select属性配置。

18、MyBatis实现一对多有几种方式,怎么操作的?

有联合查询和嵌套查询。联合查询是几个表联合查询,只查询一次,通过在resultMap里面的collection节点配置一对多的类就可以完成;嵌套查询是先查一个表,根据这个表里面的 结果的外键id,去再另外一个表里面查询数据,也是通过配置collection,但另外一个表的查询通过select节点配置

19、Mapper编写有哪几种方式?

第一种:接口实现类继承SqlSessionDaoSupport:使用此种方法需要编写mapper接口,mapper接口实现类、mapper.xml文件。

(1)在sqlMapConfig.xml中配置mapper.xml的位置:

<mappers>
        <mapper resource="mapper.xml 文件的地址" />
        <mapper resource="mapper.xml 文件的地址" />
</mappers>

(2)定义mapper接口:

(3)实现类集成SqlSessionDaoSupport:mapper方法中可以this.getSqlSession()进行数据增删改查。

(4)spring 配置:

<bean id="对象ID" class="mapper 接口的实现">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

第二种:使用org.mybatis.spring.mapper.MapperFactoryBean:

(1)在sqlMapConfig.xml中配置mapper.xml的位置,如果mapper.xml和mappre接口的名称相同且在同一个目录,这里可以不用配置

<mappers>
        <mapper resource="mapper.xml 文件的地址" />
        <mapper resource="mapper.xml 文件的地址" />
</mappers>

(2)定义mapper接口:

① mapper.xml中的namespace为mapper接口的地址

② mapper接口中的方法名和mapper.xml中的定义的statement的id保持一致

③ Spring中定义:

<bean id="" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="mapper 接口地址" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

第三种:使用mapper扫描器:

 (1)mapper.xml文件编写:

mapper.xml中的namespace为mapper接口的地址;

mapper接口中的方法名和mapper.xml中的定义的statement的id保持一致;

如果将mapper.xml和mapper接口的名称保持一致则不用在sqlMapConfig.xml中进行配置。 

(2)定义mapper接口:

注意mapper.xml的文件名和mapper的接口名称保持一致,且放在同一个目录

(3)配置mapper扫描器:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="mapper接口包地址" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

(4)使用扫描器后从spring容器中获取mapper的实现对象

20、什么是MyBatis的接口绑定?有哪些实现方式? 

 接口绑定,就是在MyBatis中任意定义接口,然后把接口里面的方法和SQL语句绑定,我们直接调用接口方法就可以,这样比起原来了SqlSession提供的方法我们可以有更加灵活的选择和设置。

接口绑定有两种实现方式

一种是通过@注解绑定

就是在接口的方法上面加上 @Select、@Update等注解,里面包含Sql语句来绑定

一种就是通过xml里面写SQL来绑定

 在这种情况下,要指定xml映射文件里面的namespace必须为接口的全路径名。当Sql语句比较简单时候,用注解绑定, 当SQL语句比较复杂时候,用xml绑定,一般用xml绑定的比较多。

xml绑定要求:

  •  Mapper接口方法名和mapper.xml中定义的每个sql的id相同;
  •  Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同;
  •  Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同;
  •  Mapper.xml文件中的namespace即是mapper接口的类路径

21、Mybatis延迟加载策略

  • 延迟加载(懒加载):

就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载。
在实际的开发过程中很多时候我们并不需要总是在加载用户信息时就一定要加载他的账户信息。这就是我们所说的延迟加载。
在真正使用数据时才发起查询,不用的时候不查询。按需加载(懒加载)。

  • 在对应的四种表关系中:

一对多,多对一,一对一,多对多
一对多,多对多:通常情况下我们都是采用延迟加载。
多对一,一对一:通常情况下我们都是采用立即加载。

  • 好处:

先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。

  • 坏处:

因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降

延迟加载的两种实现方法:

  • 使用 Collection 实现延迟加载(一对多) 
  • 使用 assocation 实现延迟加载(一对一)

开启 Mybatis 的延迟加载策略 

在 Mybatis 的配置文件 SqlMapConfig.xml 文件中添加延迟加载的配置

<!--配置参数-->
<settings>
     <!--开启Mybatis支持延迟加载-->
     <setting name="lazyLoadingEnabled" value="true"/>
     <setting name="aggressiveLazyLoading" value="false"/>
</settings>

 21.1.实现延迟加载的准备工作

1.Account 实体类

package com.keafmd.domain;

import java.io.Serializable;

@Data
public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;

    // 一对一,从表实体应该包含一个主表实体的对象引用
    private User user;
}

1.2.Account持久层 DAO 接口

package com.keafmd.dao;
import com.keafmd.domain.Account;
import java.util.List;

public interface IAccountDao {
    /**
     * 查询所有账户,同时还要获取当前账户的所属用户信息
     * @return
     */
    List<Account> findAll();

    /**
     * 根据用户id查询账户信息
     * @return
     */
    List<Account> findAccountByUid(Integer uid);
}

1.3.账户的持久层映射文件 IAccountDao.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.keafmd.dao.IAccountDao">
    <!--定义封装account和user的resultmap-->
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
    </resultMap>

    <!--配置查询所有-->
    <select id="findAll" resultMap="accountUserMap">
        select * from account
    </select>

    <!--根据用户id查询账户列表-->
    <select id="findAccountByUid" resultType="account">
        select * from account where uid = #{uid}
    </select>
</mapper>

 2.User 实体类

package com.keafmd.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Data
public class User implements Serializable {
    private Integer id;
    private String username;
    private String sex;
    private String address;
    private Date birthday;

    //一对多关系映射,主表实体应该包含从表实体的集合引用
    private List<Account> accounts;
}

 2.1.用户的持久层DAO接口 IUserDao:用于 association/collection 调用

package com.keafmd.dao;
import com.keafmd.domain.User;
import java.util.List;

public interface IUserDao {
    /**
     * 根据id查新用户信息
     * @param id
     * @return
     */
    User findById(Integer id);
}

2.2.用户的持久层映射文件 IUserDao.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.keafmd.dao.IUserDao">
    <!--根据id查询用户-->
    <select id="findById" parameterType="Integer" resultType="user">
        select * from user where id = #{id}
    </select>
</mapper>

21.2.使用 assocation 实现延迟加载(一对一) 

持久层mapper映射文件 IAccountDao.xml:(association 懒加载实现)

 对AccountDao.findAll() 接口做一对多的延时加载处理

<?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.keafmd.dao.IAccountDao">
    <!--定义封装account和user的resultmap-->
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--一对一的关系映射,配置封装user的内容
        select属性指定的内容:查询用户的唯一标志
        column属性指定的内容:用户根据id查询是,所需要的参数的值
        -->
        <association property="user" column="uid" javaType="user" 
    select="com.keafmd.dao.IUserDao.findById">
        </association>
    </resultMap>

    <!--配置查询所有-->
    <select id="findAll" resultMap="accountUserMap">
        select * from account
    </select>
</mapper>

21.3.使用 collection实现延迟加载(一对多) 

持久层mapper映射文件 IUserDao.xml:(collection 懒加载实现)

 对 UserDao.findAll() 接口做一对多的延时加载处理

<?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.keafmd.dao.IUserDao">
    <!--定义User的resultMap-->
    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <!--配置user对象中account集合的映射-->
        <collection property="accounts" ofType="account" select="com.keafmd.dao.IAccountDao.findAccountByUid" column="id"></collection>
    </resultMap>

    <!--配置查询所有-->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>
</mapper>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值