1.准备实体类
一对多写集合,用户实体User的集合List<User>作为分组实体类Groups的属性,并写出对应的get、set方法,不要在toString方法重写。
2.方式二:通过一条sql语句查询
方式二:发送一次sql语句,进行联表查询,需要注意SQL语句的性能,不需要
使用select属。
注:column属性值需要与sql语句内的字段别名(有别名时)相同。
collection——集合映射标签 出现在“一”方
属性column 数据表中关联的外键名
属性property 实体类中的另一个表的实体类作为集合属性的属性名
属性ofType: 查询结束之后的返回类型collection打开,可以嵌入子标签:
id 对方表中的主键
column 数据表中的字段名
property 实体类中的属性名
result:其他属性
column sql语句中对应数据表中的字段名
property 实体类中的属性名
3.实例展示
(1)问题描述
通过分组id,查出该该分组信息(Groups表),以及该组的所有用户信息(User表)。
(2)数据库表关系
(3)代码实现(关键代码展示):
GroupsDao层方法:
//方式一——通过一条sql语句查询 Groups getGroupById1(int gid);
GroupsDao映射文件——GroupsMapper.xml:
<!--方式二--> <select id="getGroupById1" resultMap="groupResult1"> select g.gid gid,gname,id,uname,pwd,age from groups g left join user u on g.gid=u.gid where g.gid=#{gid}; </select> <resultMap id="groupResult1" type="com.zx.pojo.Groups"> <id column="gid" property="gid"></id> <result column="gname" property="gname"></result> <!--collection集合映射 column为查询关联表的外键 property查询关联表的实体类在该实体类中的属性名(一对多属性为集合)。 --> <collection column="gid" property="users" ofType="com.zx.pojo.User"> <id column="id" property="id"></id> <result column="uname" property="uname"></result> <result column="pwd" property="pwd"></result> <result column="age" property="age"></result> </collection> </resultMap>
运行测试:
public class GroupDaoTest { @Test public void getGroupById1Test(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); GroupsDao groupsDao = sqlSession.getMapper(GroupsDao.class); Groups group = groupsDao.getGroupById1(2); System.out.println(group); System.out.println(group.getUsers()); } }
测试结果:
4.一对多集合查询两种方式的区别
(1)方式一需要两条简单sql语句,需要查询两次;
方式二需要一条多表查询sql语句,需要查询一次。
(2)方式一collection标签内se需要select属性指向第二条查询语句;
方式二collection标签内不需要select属性
(3)方式一collection标签内不需要写子标签;
方式二collection标签内需要写子标签。
(4)方式一column属性对应数据表中的字段名;
方式二column属性对应sql语句中对应数据表中的字段名(多表查询可能会起别名,有变化)。