mybatis association的两种形式

来源:互联网 发布:windows iso怎么下载 编辑:程序博客网 时间:2024/05/17 06:13
一、嵌套的resultMap
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.zsm.myBatis.day02.inner.IStudentOperation">
<!-- 定义java Bean的属性与数据库的列之间的映射 -->
<resultMap type="Teacher" id="teacherResultMap">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
<result property="gender" column="t_gender"/>
<result property="researchArea" column="research_area"/>
</resultMap>
<resultMap type="Student" id="studentResultMap">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="gender" property="gender" />
<result column="major" property="major" />
<result column="grade" property="grade"/>
<!-- 引用teacherResultMap -->
<association property="supervisor" resultMap="teacherResultMap"/>
</resultMap>

<!-- SQL语句中以"#{}"的形式引用参数 -->
<select id="getById" parameterType="int" resultMap="studentResultMap">
SELECT st.id,st.name,st.gender,st.major,st.grade,t.id t_id,t.name t_name,
     t.gender t_gender,t.research_area 
FROM student st, teacher t
WHERE st.supervisor_id = t.idAND st.id=#{id}
</select>
</mapper>


二、嵌套的select语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.zsm.myBatis.day02.inner.IStudentOperation">
<!-- 定义java Bean的属性与数据库的列之间的映射 -->
<resultMap type="Teacher" id="supervisorResultMap">  
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
<result property="gender" column="t_gender"/>
<result property="researchArea" column="research_area"/>
</resultMap>
<resultMap type="Student" id="studentResultMap">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="gender" property="gender" />
<result column="major" property="major" />
<result column="grade" property="grade"/>
<!-- 引用teacherResultMap -->
<association property="supervisor" column="supervisor_id" select="selectSupervisor"/>
</resultMap>
<!-- SQL语句中以"#{}"的形式引用参数 -->
<select id="getById" parameterType="int" resultMap="studentResultMap">
     select id,name,gender,major,grade,supervisor_id from student where id =#{id}
</select>
<select id="selectSupervisor" parameterType="int" resultMap="supervisorResultMap">
     select id,name,gender,research_areafrom teacher where id = #{id}
</select>
</mapper>
0 0
原创粉丝点击