JavaEE——Mybatis(5)--resultMap自定義結果集封裝


<!--自定義某個javaBean的封裝規則
	type:自定義規則的Java類型
	id:唯一id方便引用
	  -->
	<resultMap type="com.atguigu.mybatis.bean.Employee" id="MySimpleEmp">
		<!--指定主鍵列的封裝規則
		id定義主鍵會底層有優化;
		column:指定哪一列
		property:指定對應的javaBean屬性
		  -->
		<id column="id" property="id"/>
		<!-- 定義普通列封裝規則 -->
		<result column="last_name" property="lastName"/>
		<!-- 其他不指定的列0"email"/>
		<result column="gender" property="gender"/>
	</resultMap>
	
	<!-- resultMap:自定義結果集映射規則;  -->
	<!-- public Employee getEmpById(Integer id); -->
	<select id="getEmpById"  resultMap="MySimpleEmp">
		select * from tbl_employee where id=#{id}
	</select>

  添加外鍵約束

聯合查詢:

<!--
  場景一:
  查詢Employee的同時查詢員工對應的部門
  Employee===Department
  一個員工有與之對應的部門信息;
  id last_name gender d_id did dept_name (private Department dept;)
  -->

<!--
  聯合查詢:級聯屬性封裝結果集
-->

<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		<result column="did" property="dept.id"/>
		<result column="dept_name" property="dept.departmentName"/>
	</resultMap>

<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="MyDifEmp">
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>

  

<!--
  使用association定義關聯的單個對象的封裝規則;
-->

<!-- association可以指定聯合的javaBean對象
  property="dept":指定哪個屬性是聯合的對象
  javaType:指定這個屬性對象的類型[不能省略]
-->

<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp2">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		
		<!--  association可以指定聯合的javaBean對象
		property="dept":指定哪個屬性是聯合的對象
		javaType:指定這個屬性對象的類型[不能省略]
		-->
		<association property="dept" javaType="com.atguigu.mybatis.bean.Department">
			<id column="did" property="id"/>
			<result column="dept_name" property="departmentName"/>
		</association>
	</resultMap>
	<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="MyDifEmp">
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM