您的位置:首页 > 其它

MyBatis 一对多 多对一 自关联 例子

2017-07-14 17:14 399 查看
public interface IDepet {

public Dept getAll(int id);

public Dept  getAllMutlSql(int id);

}
<mapper namespace="cn.hello.dao.IDepet">
<resultMap id="deptMap" type="Dept">
<id column="deptNo" property="deptNo"></id>
<result column="deptName" property="deptName"></result>
<collection property="emps" ofType="Emp">
<id column="empNo" property="empNo"></id>
<result column="empName" property="empName"></result>
</collection>
</resultMap>

<resultMap id="deptMapMutlSql" type="Dept">
<id column="deptNo" property="deptNo"></id>
<result column="deptName" property="deptName"></result>
<collection property="emps" ofType="Emp" select="selectDeptNo" column="deptNo"></collection>
</resultMap>
<!--一对多 多条SQ-->
<select id="selectDeptNo" resultType="Emp">
SELECT  * FROM emp WHERE  deptNo=#{deptNo}
</select>
<!--一对多 单条SQL-->
<select id="getAll" resultMap="deptMap">
select dept.deptNo,deptName,empNo,empName
from dept,emp
where dept.deptNo=emp.deptNo
and dept.deptNo=#{deptNo}
</select>
<!--一对多 多条SQ-->
<select id="getAllMutlSql" resultMap="deptMapMutlSql">
select deptNo,deptName
from dept
where deptNo=#{deptNo}
</select>
</mapper>
public interface IEmp {

public Emp SelectEmpNo(int id);

public  Emp  SelectEmpNoMutile(int id);
}
<mapper namespace="cn.hello.dao.IEmp">

<resultMap id="empMap" type="Emp">
<id column="empNo" property="empNo"></id>
<result column="empName" property="empName"></result>
<association property="dept" javaType="Dept">
<id column="deptNo" property="deptNo"></id>
<result column="deptName" property="deptName"></result>
</association>
</resultMap>

<resultMap id="empMapMuit" type="Emp">
<id column="empNo" property="empNo"></id>
<result column="empName" property="empName"></result>
<association property="dept" javaType="Dept" select="selectDeptNo" column="deptNo"></association>
</resultMap>
<!--多对一  多条SQL-->
<select id="selectDeptNo" resultType="Dept">
SELECT  * FROM  dept WHERE deptNo=#{deptNo}
</select>

<!--多对一 一条SQL-->

<select id="SelectEmpNo" resultMap="empMap">
select dept.deptNo,deptName,empNo,empName
from dept,emp
where dept.deptNo=emp.deptNo
and emp.empNo=#{empNo}
</select>

<!--多对一  多条SQL-->
<select id="SelectEmpNoMutile" resultMap="empMapMuit">
SELECT deptNo,empNo,empName
FROM  emp
WHERE  empNo=#{empNo}
</select>
</mapper>
public interface ICategory {
public List<Category>  getChildreByPid(int id);

}
<mapper namespace="cn.hello.dao.ICategory">

<!--自关联-->
<resultMap id="CateMap" type="Category">
<id column="cid" property="cid"></id>
<result column="cname" property="cname"></result>
<result column="pid" property="pid"></result>
<collection property="cates" ofType="Category" select="getChildreByPid" column="cid"></collection>
</resultMap>

<select id="getChildreByPid" resultMap="CateMap">
SELECT  * FROM  category WHERE pid=#{pid}
</select>
</mapper>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: