MyBatis中的三种映射方法(1)

一、一对一映射:

1、先在数据库里边建两张表,学生表和地址表(规定一个学生只能有一个家庭地址,一个家庭地址只能对应一个学生),并插入一些数据信息;

2、在sts中创建实体类,Student和Address,并且Student中有一个Address属性;

3、创建映射接口StudentMapper,创建查询数据的方法;

public interface StudentMapper {
	//查询所有学生,地址
	List<Student> findStudentsWithAddress();

}

4、在映射文件里面进行对映射接口的配置;

(1)嵌套结果(把所有的sql语句都写在一起,即执行sql语句时只执行一句sql语句,把执行结果嵌套在一起):

<resultMap id="findStudentsWithAddressResult" type="com.briup.oneToone.Student">
		<id property="studId" column="id"/>
		<result property="name" column="name"/>
		<result property="email" column="email"/>
		<result property="dob" column="dob"/>
		<result property="phone" column="phone"/>
		<association property="address" resultMap="AddressResult"></association>	
</resultMap>
	
<resultMap id="AddressResult" type="com.briup.oneToone.Address">
		<id property="addrId" column="addr_id"/>
		<result property="street" column="street"/>
		<result property="city" column="city"/>
		<result property="state" column="state"/>
		<result property="zip" column="zip"/>
		<result property="country" column="country"/>
</resultMap>
	
<!-- List<Student> findStudentsWithAddress(); -->
<select id="findStudentsWithAddress" resultMap="findStudentsWithAddressResult">
	select s.id,s.name,s.email,s.dob,s.phone,
		a.addr_id,a.street,a.city,a.state,a.zip,a.country
	from students s left join addresses a
	on s.addr_id=a.addr_id
</select>

(2)嵌套查询

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清梦扰i

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值