mybatis入门(四)---ResultMap
程序员文章站
2022-07-13 16:58:38
...
承接三,通过resultMap实现一对多。
1.在数据库中添加表t_pet,代码如下:
create table t_pet(id number(11), petname varchar2(11),userid number(11)); alter table t_pet add constraint pk_pet_id primary key(id); update t_pet set userid = '4';
2.在User类中加入对象List<Pet> pets;
3.修改配置文件User.xml,在User.xml中加入如下内容:
<!-- 一对多关联 --> <resultMap type="User" id="userResult1"> <id property="id" column="user_id" /> <result property="userName" column="user_name" /> <collection property="pets" ofType="Pet"> <id property="id" column="pet_id" /> <result property="petName" column="pet_name" /> <result property="petColor" column="pet_color" /> </collection> </resultMap> <select id="select2" parameterType="int" resultMap="userResult1"> select u.id as user_id, u.username as user_name, p.userid as pet_user_id, p.id as pet_id, p.petname as pet_name, p.petcolor as pet_color from t_user u,t_pet p where u.id = p.userid and u.id = #{id} </select>
上面<collection> 标签实现一对多的功能。
4.在Test中进行测试。
推荐阅读