//類 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