Java日记之Mybatis一对一,一对多

这个标题无意的表情包刚刚好就是现在的状态😴

一.引入

在还没学这里之前,想一想 , 我们在给数据库字段起名的时候 , 通常是这样的user_id , 可是按照Java的编程规范 , 我们的属性名应该是这样的userId
咦~ 这就很玄学了 , 那咋整呢? 于是就有了今天的知识Mybatis的resultMap映射

二.解决上述问题

那当然是自定义映射规则啦

<!-- 映射规则 -->
	<resultMap id="OrdersAndUser" type="order">
		<id column="id" property="id"/>
		<result column="user_id" property="userId"/> ←这里这里
		<result column="number" property="number"/>
		<result column="createtime" property="createtime"/>
		<result column="note" property="note"/>
		
		<association property="myuser" javaType="user">
			<id column="tid" property="id"/>
			<result column="username" property="username"/>
			<result column="pwd" property="pwd"/>
			<result column="sex" property="sex"/>
			<result column="age" property="age"/>
		</association>

	</resultMap>
	<select id="selectOrderAndUser" resultMap="OrdersAndUser">
		
		SELECT orders.*,user.id tid,user.age,user.pwd,user.sex,user.username 
		FROM orders ,USER 
		WHERE user.id=orders.user_id
	</select>

这里的<select>标签中,resultMap属性对应,上面<resultMap></~>标签的id

三.一对多映射

一个对象对应多个对象 , 查一个用户并且查出所有与它关联的记录

<resultMap type="user" id="UserAndOrders">
		<id column="id" property="id"/>
		<result column="username" property="username"/>
		<result column="sex" property="sex"/>
		<result column="age" property="age"/>
		<result column="pwd" property="pwd"/>
		
		<collection ofType="order" property="list"> 
		<!-- ofType  结构中的泛型  list 属性名 -->
			<id column="id" property="id" />
			<result column="user_id" property="userId" />
			<result column="number" property="number" />
			<result column="createtime" property="createtime" />
		</collection>
		
	</resultMap>

ofType 是结构中的泛型的别名 , list 类中的属性名 , 一对多用到的是<collection></~>

四.一对一映射

<resultMap type="scores" id="ScoAndStu">
		
			<id column="SID" property="sid" />
			<result column="stuCode" property="stuCode" />
			<result column="Course" property="course" />
			<result column="Score" property="score" />
		
		<association property="onestudent" javaType="student">
			<id column="Code" property="code"/>
			<result column="Name" property="name"/>
			<result column="College" property="college"/>
		</association>
	</resultMap>	
	
	<select id="selectScoAndStu" resultMap="ScoAndStu">
		SELECT student.*,scores.Course,scores.Score,scores.SID,
		scores.stuCode 
		FROM student,scores 
		WHERE student.Code=scores.stuCode;
	</select>

用于处理一个记录对应一个特定记录的情况 ,比方说 :一个订单只对应一个用户<association></~>property是类中的属性名,JavaType是property的类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值