MyBatis的关联查询之自关联

自关联

一、entity实体类

public class City {
private Integer cid;
private String cname;
private Integer pid; //自关联集合 代表的是当前City对象的自己集合
public List<City> childCitys; public Integer getCid() {
return cid;
} public void setCid(Integer cid) {
this.cid = cid;
} public String getCname() {
return cname;
} public void setCname(String cname) {
this.cname = cname;
} public Integer getPid() {
return pid;
} public void setPid(Integer pid) {
this.pid = pid;
} public List<City> getChildCitys() {
return childCitys;
} public void setChildCitys(List<City> childCitys) {
this.childCitys = childCitys;
} @Override
public String toString() {
return "City{" +
"cid=" + cid +
", cname='" + cname + '\'' +
", pid=" + pid +
", childCitys=" + childCitys +
'}';
}
}

二、dao层

//自关联  查询河南省下所有子集
public City getCityAndChild(Integer cid);

三、dao.xml 小配置

<!--自关联-->
<resultMap id="CityAndChildCity" type="com.marketsys.entity.City">
<id column="cid" property="cid"></id>
<result column="cname" property="cname"></result>
<result column="pid" property="pid"></result>
<collection property="childCitys" ofType="com.marketsys.entity.City" select="getCity" column="cid">
<id column="cid" property="cid"></id>
<result column="cname" property="cname"></result>
<result column="pid" property="pid"></result>
</collection>
</resultMap>
<select id="getCityAndChild" resultMap="CityAndChildCity">
select * from city where cid=#{cid}
</select>
<select id="getCity" resultMap="CityAndChildCity">
select * from city where pid=#{cid}
</select>

四、test测试类

SqlSession sqlSession= MybatisUtil.getSqlSession();
URoleTestDao mapper=sqlSession.getMapper(URoleTestDao.class); //自关联
@Test
public void test4(){
City city = mapper.getCityAndChild(410000);
System.out.println(city.toString());
}
05-23 03:41