//类 public class Oldman { private int id; private String name; private String sex; //private int age; private String st; private String hj;//户籍 private String sfz;//身份证 //AA BB CC DDDD EE FF HH I J private String csny;//出生年月 private String jjlxr;//紧急联系人 private String phone;//电话 private String adress;//地址 private Bed bed;//床位 private Hugong hg;//护工 }
Mapper.XML中 //做好映射 <resultMap id="OldmanResult" type="com.shiro.YangLaoYuan.entity.Oldman"> <id property="id" column="oldman_id" /> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="sfz" column="sfz"/> <result property="st" column="st"/> <result property="hj" column="hj"/> <result property="jjlxr" column="jjlxr"/> <result property="phone" column="phone"/> <result property="adress" column="adress"/> <result property="rz" column="rz"/> <result property="cy" column="cy"/> <result property="desc" column="desc"/> //该标签 <association property="hg" column="oldman_hg_id" javaType="com.shiro.YangLaoYuan.entity.Hugong" resultMap="HugongResult"/> <association property="bed" column="oldman_bed_id" javaType="com.shiro.YangLaoYuan.entity.Bed" resultMap="BedResult"/> </resultMap> //护工类型 <resultMap id="HugongResult" type="com.shiro.YangLaoYuan.entity.Hugong"> <id property="id" column="hugong_id"/> <result property="name" column="hugong_name"/> </resultMap> //床位类型 <resultMap id="BedResult" type="com.shiro.YangLaoYuan.entity.Bed"> <id property="id" column="bed_id"/> <result property="info" column="bed_info"/> </resultMap>
//select语句
<select id="findOldmans" resultMap="OldmanResult">
SELECT
a.id AS oldman_id,
a.name,
a.sex,
a.sfz,
a.st,
a.hj,
a.jjlxr,
a.phone,
a.adress,
b.id AS bed_id,
a.bed AS oldman_bed_id,
b.info AS bed_info,
a.hg AS oldman_hg_id,
c.id AS hugong_id,
c.name AS hugong_name,
a.rz,
a.cy,
a.DESC
FROM
sys_oldman a
LEFT JOIN sys_bed b ON a.bed = b.id
LEFT JOIN sys_hugong c ON a.hg = c.id
</select>
总结:
Get 和set以及toString方法已经省略,不要忘记,没有get和set方法时会报错滴。
//主键 <id property="id" column="oldman_id" /> //result 代表返回的一般结果的映射 column是数据库返回的列名 property则是我们类中的定义名 <result property="name" column="name"/> //association 是一对一 或 多对一 咱们的一个老人对应一个床位和一个护工,所以使用一对一的方式 如果要通过本对象的1来获取多可以使用collection <association property="hg" column="oldman_hg_id" javaType="com.shiro.YangLaoYuan.entity.Hugong" resultMap="HugongResult"/>
如果要深入理解association/collection可参阅https://blog.51cto.com/yuqian2203/2130538