Mybatis的多表的联合查询

一对一(user表和card表 身份证对应关系)

数据库:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `sex` char(1) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) 

CREATE TABLE `card` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `num` varchar(32) DEFAULT NULL,
  `per_fk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

查询每个人对应的user表中全部信息和card表中的身份证号num

  1. 表与表关系---->实体与实体
  2. 在其中一方加入另一方的实体属性(在User 类加Card实体属性,set,get方法)
  • 编写User的自定义结果类型resultMap(这是都是手动映射)
    id设为reuse,下面要重复使用
    column:数据库中字段
    property:实体类中属性
<resultMap type="user" id="reuse">
	<id column="id" property="id"/>
	<result column="username" property="username"/>
	<result column="birthday" property="birthday"/>
	<result column="sex" property="sex"/>
	<result column="address" property="address"/>
</resultMap>
  • 第一种查询方式
    property:自定义类型的属性名(User中的card)
    javaType:指定属性的类型com.yx.bean.Card
    如果property中为自定义类型,要用association和javaType
<resultMap id="u_c1" type="user" extends="reuse">
	<!--
		property:自定义类型的属性名(User中的card)
		javaType:指定属性的类型com.yx.bean.Card
	-->
	<!--如果property中为自定义类型,要用association和javaType-->
	<association property="card" javaType="card">
		<!--
			column:数据库中字段
			property:实体类中属性
		-->
		<result column="num" property="num"/>
	</association>
</resultMap>

<select id="one2one1" resultMap="u_c1"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值