在上一篇一对一(http://t.cn/RtRMfxi)建表的基础上,再建立一张游戏账号表,一个学生可能有多个游戏账号:
-- f_account
CREATE TABLE `f_account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`account_num` varchar(20) NOT NULL COMMENT '账号',
`u_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `f_account_ibfk_1` (`u_id`),
CONSTRAINT `f_account_ibfk_1` FOREIGN KEY (`u_id`) REFERENCES `f_stu` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
修改配置文件,添加一个select方法:
tips:resultMap可以继承,collection标签要使用ofType,association要有column属性和javaType.
<resultMap type="stu" id="stuAndCardAndAccountResultMap"
extends="stuAndCardResultMap">
<collection property="accounts" ofType="Account">
<id column="account_id" property="id"/>
<result column="account_num" property="accountNum"/>
<result column="u_id" property="uId"/>
</collection>
</resultMap>
<!-- 查询出拥有游戏账号的人 -->
<select id="findStuAndCardAndAccountResultMap" resultMap="stuAndCardAndAccountResultMap">
SELECT
A.*, B.card_num, C.account_num, C.id AS account_id, C.u_id
FROM f_stu A
LEFT JOIN f_account C ON C.u_id = A.id
LEFT JOIN f_IDcards B ON A.id = B.u_id
WHERE !ISNULL(C.account_num)
ORDER BY A.id
</select>
在对应的mapper代理接口中添加此方法,进行测试:
数据可以自己添加一些测试数据.