一、需求:根据Mybatis实现2级级联的查询。
根据省的id查询它下面所有的市信息。
二、实现步骤
方法一:
思想: 此种情况是“一对多”,我们在一的mapper.xml中,用collection定义多的一个集合即可。
property ---> 对应实体类中,多的那个子类,list ofType ---> 对应子类的试题类型 column ----> 父类传递给子类查询的外键 select ----> 子类查询的方法
1.定义父类+子类的实体类
package com.imocc.mall.pojo; import lombok.Data; import java.util.List; /** * @author wy */ @Data public class Province { private Integer id; private String provinceid; private String province; private List<City> list; @Override public String toString() { return "Province{" + "id=" + id + ", provinceid=‘" + provinceid + ‘\‘‘ + ", province=‘" + province + ‘\‘‘ + ", list=" + list + ‘}‘; } }
package com.imocc.mall.pojo; import lombok.Data; @Data public class City { private Integer id; private String cityid; private String city; private String father; }
2.mapper类
2. mapperxml文件
3. 测试
JDBC Connection [[email protected] wrapping [email protected]] will not be managed by Spring ==> Preparing: select * from hat_province where provinceID =? ==> Parameters: 110000(String) <== Columns: id, provinceID, province <== Row: 1, 110000, 北京市 ====> Preparing: select id, cityID, city, father from hat_city where father = ? ====> Parameters: 110000(String) <==== Columns: id, cityID, city, father <==== Row: 1, 110100, 市辖区, 110000 <==== Row: 2, 110200, 县, 110000 <==== Total: 2 <== Total: 1 Closing non transactional SqlSession [[email protected]] Province{id=1, provinceid=‘110000‘, province=‘北京市‘, list=[City(id=1, cityid=110100, city=市辖区, father=110000), City(id=2, cityid=110200, city=县, father=110000)]}
原文地址:https://www.cnblogs.com/Edward-Wang/p/12080365.html
时间: 2024-11-01 21:49:21