使用mybatis程序开发中数据有一对多的时候mapper配置。
一、参数解释
namespace表示配置文件对应的那个接口文件,select中id表示对应接口文件中的抽象方法,resultMap表示sql返回数据列和实体类字段对应关系,collection表示role队形中有一个属性是集合,这集合的名称就是collection的property的值。
resultMap中 type表示返回数据实例化的类型,id、result、collection中的property对应实体类的属性,id、result中的column对应返回数据表的列名,collection中的ofType表示返回集合数据中的实体类名称
<mapper namespace="com.ccdd.dd.oo"> <resultMap id="roleMap" type="role"> <id property="roleId" column="rID"></id> <result property="roleName" column="ROLE_NAME"></result> <result property="roleDesc" column="ROLE_DESC"></result> <collection property="users" ofType="user"> <id property="id" column="id"></id> <result property="username" column="username"></result> <result property="address" column="address"></result> <result property="sex" column="sex"></result> <result property="birthday" column="birthday"></result> </collection> </resultMap> <select id="findAll" resultMap="roleMap"> select u.*,r.id as rid,r.role_name,r.role_desc from role r left outer join user_role ur on rid=ur.rid left outer join user u on ur.uid=u.id </select> </mapper>
二、对应实体类
public class Role implements Serializable { private Integer roleId; private String roleName; private String roleDesc; private List<User> users; public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleDesc() { return roleDesc; } public void setRoleDesc(String roleDesc) { this.roleDesc = roleDesc; } @Override public String toString() { return "Role{" + "roleId=" + roleId + ", roleName='" + roleName + '\'' + ", roleDesc='" + roleDesc + '\'' + '}'; } }
public class User implements Serializable { private Integer id; private String username; private String address; private String sex; private Date birthday; private List<Role> roles; public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", address='" + address + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + ", roles=" + roles + '}'; } }
三、SQL语句查询结果
仔细分析,一一对应关系。