我是靠谱客的博主 聪慧飞机,这篇文章主要介绍MyBatis如何实现多表查询,现在分享给大家,希望可以做个参考。

MyBatis如何实现多表查询(一对一、一对多)

方式一:在实体类中添加对应的外部属性,在sqlMapper.xml中配置对应的resultMap标签

1.一对一:在resultMap标签中使用 association 标签进行级联映射

<resultMap type="主表javaBean类型" id="映射的id">
 		<!-- 主表属性映射 -->
 		<id column="数据库主键字段" property="实体类对应属性"/>
 		<result column="数据库非主键字段" property="实体类对应属性"/>
 		<!-- 副表属性映射 -->
 		<association property="实体类对应外部属性" javaType="副表javaBean类型" fetchType="eager|lazy">
 			<id column="数据库主键字段" property="实体类对应属性"/>
 			<result column="数据库非主键字段" property="实体类对应属性"/>
 		</association>
 </resultMap>

2.一对多:在resultMap 标签中使用collection 标签进行级联映射

<resultMap type="主表javaBean类型" id="映射的id">
 		<!-- 主表属性映射 -->
 		<id column="数据库主键字段" property="实体类对应属性"/>
 		<result column="数据库非主键字段" property="实体类对应属性"/>
 		<!-- 副表属性映射 -->
 		<collection property="实体类对应外部属性" ofType="副表javaBean类型" fetchType="eager|lazy">
 			<id column="数据库主键字段" property="实体类对应属性"/>
 			<result column="数据库非主键字段" property="实体类对应属性"/>
 		</collection>
 	</resultMap>
方式二:在实体类中添加对应的外部属性,在sqlMapper.java接口中使用注解方式进行映射

1.一对一:在@Results 注解中的@Result注解中使用@One注解

@Results({
	@Result(id = true,column = "数据库主键字段",property = "实体类对应属性"),
	@Result(id = false,column = "数据库非主键字段",property = "数据库非主键字段"),
    @Result(id = false,column = "副表的主键字段",property = "实体类对应外部属性",
           one = @One(select = "包名.类名.指定执行的查询方法名"))
})

2.一对多:在@Results 注解中的@Result 注解中使用@Many注解

@Results({
	@Result(id = true,column = "数据库主键字段",property = "实体类对应属性"),
	@Result(id = false,column = "数据库非主键字段",property = "数据库非主键字段"),
    @Result(id = false,column = "副表的主键字段",property = "实体类对应外部属性",
           many = @Many(select = "包名.类名.指定执行的查询方法名"))
})

最后

以上就是聪慧飞机最近收集整理的关于MyBatis如何实现多表查询的全部内容,更多相关MyBatis如何实现多表查询内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部