MyBatis 关系映射XML配置
关系映射
在我看来这些实体类就没啥太大关联关系,不就是一个sql语句解决的问题,直接多表查询就完事,程序将它设置关联就好
xml里面配置也是配置了sql语句,下面给出几个关系的小毛驴(xml)
一对多
<mapper namespace="com.entity.UserMapper"> <!--一对多关联查询 --> <resultMap id="user_info" type="com.entity.User"> <result property="id" column="id" /> <result property="username" column="username"/> <result property="password" column="password"/> <collection property="userInfos" ofType="com.entity.UserInfo" column="uid"> <result property="id" column="id"/> <result property="address" column="address"/> </collection> </resultMap> <select id="getUser" resultMap="user_info"> select * from user u,userinfo i where u.id=i.uid and u.id=#{id} </select> </mapper>
实体类,给出字段,自己get和set
/** * * @author 坚持到你GL * */ public class User { private int id; private String username; private String password; private List<UserInfo> userInfos;
/** * * @author 坚持到你GL * */ public class UserInfo { private int id; private String address; private int uid;
多对多
<mapper namespace="com.entity.UserMapper"> <!--多对多 --> <resultMap id="ug" type="com.entity.User"> <result property="id" column="id" /> <result property="username" column="username"/> <result property="password" column="password"/> <collection property="groups" ofType="com.entity.Group"> <id property="id" column="gid"/> <result property="info" column="info"/> </collection> </resultMap> <select id="getUserGroup" resultMap="ug"> select * from user u, `group` g,user_group ug where g.id=#{id} and u.id=ug.uid and g.id=ug.gid </select> </mapper>
实体类
/** * * @author 坚持到你GL * */ public class User { private int id; private String username; private String password; private List<Group> groups;
/** * * @author 坚持到你GL * */ public class Group { private int id; private String info; private List<User>users;
/** * 中间表 * @author 坚持到你GL * */ public class UserGroup { private int id; private int uid; private int gid;
一对一
关键在于
<collection property="groups" ofType="com.entity.Group">将ofType变成javaType
推荐个网址
【版本声明】本文为博主原创文章,转载请注明出处
坚定信念,持之以恒
作者:坚持到底gl
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。