一对一

在SysUser 类中增加SysRole字段。
1、sql语句将role.role_name映射到role.roleName上。


2、还可以在XML 映射文件中配置结果映射。
<resultMap 前缀。


3、MyBatis是支持resultMap继承,因此可以简化上面的resultMap配置
<resultMap id= "userRoleMap" extends= "userMap" type= "SysUser">
<result property= "role.id" column="role_id "/>
<result property= "role.roleName" column= "role_name"/>
<result property= "role.createTime" column ="role_create_time" jdbcType= "TIMESTAMP"/>
</resultMap>


4、使用resultMap的association标签配置
<resultMap id= "userRoleMap" extends= "userMap" type= "SysUser">
<association property="role" columnPrefix="role_" javaType="SysRole">
<result property= "id" column="role_id "/>
<result property= "roleName" column= "role_name"/>
<result property= "createTime" column ="create_time" jdbcType= "TIMESTAMP"/>
</association>
</resultMap>
association标签的属性property对应实体类中的属性名,必填项。另外我们还配置了columnPrefix="role_",在写SQL的时候,和sys_role表相关的查询列的别名都要有"role_"前缀,在内部result配置column时,需要去掉前缀。sql:r.id role_id, r.role_name role_role_name, r.create_time role_create_time。


5、使用association 配置时还可以使用resultMap 属性配置成一个已经存在的resultMap
<resultMap id= "roleMap" type = "SysRole">
<id property="id" column="id"/>
<result property="roleName" column= "role_name"/>
<result property="createTime" column="create_time" jdbcType = "TIMESTAMP"/>
</resultMap>
<resultMap />
</resultMap>
上面的情况都是一种情况,这种方式的好处是减少数据库查询次数,减轻数据库的压力。缺点是由于要在应用服务器上将结果映射到不同的类上,因此也会增加应用服务器的压力。当一定会使用到嵌套结果,并且整个复杂的SQL执行速度很快时,建议使用这种方法。


还可以利用简单的SQL 通过多次查询转换为我们需要的结果,最后会将结果组合成一个对象。

<resultMap id = "userRoleMapSelect" extends = "userMap" type= "SysUser">
<association property="role" column="{id=role_id}" select="test.mybatis.simple.mapper.RoleMapper.selectRoleById" />
</resultMap>
<select >
select u.id, u.user_name, u.user_password, u.user_email, u.user_info,u.head_img, u.create_time,
ur.role_id
from sys_user u
join sys_user_role ur on u.id = ur.user_id
where u.id= #{id}
</select>
association 属性 select :另一个查询的id, MyBatis 会额外执行这个查询。
column :列名(或别名),将主查询中列的结果作为嵌套查询的参数,配置方式如 column = {propl=coll , prop2=col2}。
fetchType :数据加载方式,可选值为lazy 和eager,分别为延迟加载和积极加载,这个配置会覆盖全局的lazyLoadingEnabled 配置。

问题:如果主查询结果不是1条数据,而是N条数据,那就会出现N+1问题。主SQL 会查询一次,查询出N 条结果,这N条结果要各自执行一次查询,那就需要进行N次查询。


解决办法:fetchType="lazy"
<resultMap id = "userRoleMapSelect" extends = "userMap" type= "SysUser">
<association property="role" column="{id=role_id}"
  select="test.mybatis.simple.mapper.RoleMapper.selectRoleById" fetchType="lazy"/>
</resultMap>
<select >
  select u.id, u.user_name, u.user_password, u.user_email, u.user_info,u.head_img, u.create_time,
  ur.role_id
from sys_user u
  join sys_user_role ur on u.id = ur.user_id
  where u.id= #{id}
</select >

相关文章:

  • 2021-04-08
  • 2021-05-27
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2022-01-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-10
  • 2021-11-27
  • 2022-12-23
  • 2021-04-20
相关资源
相似解决方案