Mybatis两张表同时查询所遇问题

两张表
员工表(Employee): id last_name email gender
部门表(Dept) d_id(与上述id一样)dept_name

//	使用association进行分布查询
//public Employee getEmpByIdStep(Integer id);

	<resultMap id="MyEmpByStep" type="com.atguigu.mybatis.dao/.Employee">
//1.先按照员工id查询员工信息
//2.根据查询员工信息中的d_id值去部门表中查出部门信息
//3.部门设置到员工中
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
<!--		association定义关联对象的封装规则(放另一张表)-->
		<association property="dept"
					 select="com/atguigu/mybatis/dao/DepartmentMapper.getDeptById"
					 column="d_id">
		</association>
	</resultMap>

	<select id="getEmpByIdStep" resultMap="MyEmpByStep">
		select * feom tbl_employee where id=#{id}
	</select>

延迟加载
Employee==>Dept (Employee中关联Dept)
我们每次查询Employee对象的时候,一起查出来,但是我们希望部门信息在我们使用时再进行查询,于是在分段查询的基础上,加上两个配置(在总配置文件中)

<settings>
//驼峰命名法开启
		<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--		显示的指定我们需要更改的值-->
//延迟加载
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>

两个表联合查询,其中有一个属性是集合时

与association类似,association属于定义单个对象级联,ollection定义集合类型属性的封装规则

<!--	public class Department{
			private Integer id;
			private String departmentName;
			private List<Employee> emps;   这是一个集合属性
}
-->

正式代码:
<resultMap id="MyDept" type="com.atguigu.mybatis.bean.Department.java">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<result column="dept_name" property="departmentName"/>
<!--		collection定义集合类型属性的封装规则-->
		<collection property="emps" ofType="com.atguigu.mybatis.bean.Employee">
			<id column="eid" property="id"/>
			<result column="last_name" property="lastName"/>
			<result column="email" property="email"/>
			<result column="gender" property="gender"/>
		</collection>
	</resultMap>

	<select id="getDeptByIdPlus" resultMap="MyDept">
		select d.id,d.dept_name dept_name,e.id eid,e.last_name last_name,e.email email,e.gender gender
		from tbl_dept d
		left join tbk_employee e
		on d.id=e.d_id
		where d.id=#{id}
	</select>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值