多表连接
参考 https://www.jianshu.com/p/018c0f083501
association标签
association标签:一对一 和 多对一
-
作用:将关联查询信息映射到一个pojo类中。
-
两种方式:
-
只写一个映射文件StudentMapper.xml(CardMapper不能在其他映射文件中复用)
<mapper namespace="mybatis_test.StudentMapper"> <resultMap id="studentMap" type="mybatis_test.Student"> <id column="id" property="id"/> <result column="sname" property="name"/> <association property="card" javaType="mybatis_test.Card"> <id column="cid" property="id"/> <result column="cnum" property="num"/> </association> </resultMap> <select id="findById" resultMap="studentMap"> select * from students s,cards c where s.scid=c.cid and s.id=#{id} </select> </mapper>
-
写两个映射文件StudentMapper.xml和CardMapper(能在其他映射文件中复用)
<!--CardMapper.xml--> <mapper namespace="mybatis_test.CardMapper"> <resultMap id="cardMap" type="mybatis_test.Card"> <id column="cid" property="id"/> <result column="cnum" property="num"/> </resultMap> </mapper> <!--StudentMapper.xml--> <mapper namespace="mybatis_test.StudentMapper"> <resultMap id="studentMap" type="mybatis_test.Student"> <id column="id" property="id"/> <result column="sname" property="name"/> <association property="card" resultMap="cardMap"/> </resultMap> </mapper>
collection标签
collection标签:一对多
-
作用:将关联查询信息映射到一个list集合中。
-
场合:为了方便获取关联信息可以使用collection将关联信息映射到list集合中,比如:查询一个人有多个手机
-
ofType属性一定不能少,collection 装的元素类型是啥ofType的值就是啥
两种方式:
-
只写一个映射文件UserMapper.xml(PhoneMapper不能在其他映射文件中复用)
<mapper namespace="mybatis_test.UserMapper"> <resultMap id="userMap" type="mybatis_test.User"> <id column="uid" property="id"/> <result column="uname" property="name"/> <collection property="phones" ofType="mybatis_test.Phone" > <result column="pname" property="name"/> </collection> </resultMap> <select id="find" resultMap="userMap"> select u.uid,u.uname,p.pname from user u,phone p where u.uid=p.u_pid and u.uid=#{id}; </select> </mapper>
-
写两个映射文件UserMapper.xml和PhoneMapper(能在其他映射文件中复用)
...
由于SQL语句全是由我们自己写,如果我们返回的数据类型在当前的实体中是不够封装的话,那么我们只要再关联对应的映射属性就行了!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具