mybatis04——一对一和一对多查询

在sql语句查询时常常并不是对一张表做查询,而是同时对两张或两张以上的表做查询操作。当然可以把关联两张表的查询拆分成两次单表查询,但这样肯定导致性能利用率下降。与数据库的每次互动都要占据一定的资源,能够减少互动是原则。
举例:以用户表和订单表举例,一个订单只能属于一个用户,这是一对一,那么orders的entity应该加上这么一行代码

private User user;

一个用户可以拥有很多订单,这是一对多,那么user的entity应该加上代码:

private List<Orders> orders;

xml文件上的实现:
一对一:

	<select id="findOrders" resultMap="resultMap1">
		SELECT orders.id,orders.user_id,orders.number,orders.note,user.id AS uid,user.username,user.sex,user.address
		FROM orders
		INNER JOIN USER
   		ON(orders.user_id = user.id)
	</select>
	<resultMap type="com.mybatis.entity.Orders" id="resultMap1">
		<id property="id" column="id"/>
		<result property="user_id" column="user_id"/>
		<result property="number" column="number"/>
		<result property="note" column="note"/>
		<association property="user" javaType="com.mybatis.entity.User">
			<id property="id" column="uid"/>
			<result property="username" column="username"/>
			<result property="sex" column="sex"/>
			<result property="address" column="address"/>
		</association>
	</resultMap>
一对多:
`<select id="findUsers" resultMap="resultMap2">
	SELECT user.id,user.username,user.sex,user.address, orders.id AS oid,orders.user_id,orders.number,orders.note
	FROM USER
	INNER JOIN orders
	ON(orders.`user_id` = user.`id`)
</select>
<resultMap type="com.mybatis.entity.User" id="resultMap2">
	<id property="id" column="id"/>
	<result property="username" column="username"/>
	<result property="sex" column="sex"/>
	<result property="address" column="address"/>
	<collection property="orders" ofType="com.mybatis.entity.Orders">
		<id property="id" column="oid"/>
		<result property="user_id" column="user_id"/>
		<result property="number" column="number"/>
		<result property="note" column="note"/>
	</collection>
</resultMap>`
主要是在结果类型上做一些对应,如果两张表有重复字段,做一下重命名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值