前面几篇博客介绍的都是单表映射的一些操作,然而在我们的实际项目中往往是用到多表映射。至于多表映射的关键要用到mybitis的association来加以实现。
这篇介绍的是多表中的多对一表关联查询 先做一些准备工作 创建两张表:一张是用户,一张是用户所对应的移动手机,一户用户可以有部移动手机。 这是用户t_user表这是移动电话t_mobile表
创建表对应的JavaBean对象
User对象
- package com.jefry;
- public class User {
- private int id;
- private String userName;
- private String password;
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- }
- package com.jefry;
- public class Mobile {
- private int id;
- private String telnumber;
- private User user;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getTelnumber() {
- return telnumber;
- }
- public void setTelnumber(String telnumber) {
- this.telnumber = telnumber;
- }
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- }
- <typeAliases>
- <typeAlias alias="User" type="com.jefry.User"/>
- <typeAlias alias="Mobile" type="com.jefry.Mobile"/>
- </typeAliases>
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="mobile">
- <resultMap id="userResultMap" type="Mobile">
- <id property="id" column="id"/>
- <result property="telnumber" column="telnumber"/>
- <association property="user" javaType="User">
- <id property="id" column="id"/>
- <result property="userName" column="name"/>
- <result property="password" column="pass"/>
- </association>
- </resultMap>
- <!--多表查询操作-->
- <select id="selectMobile" parameterType="int" resultMap="userResultMap" >
- <!--分别为mobile的主键id与user的主键id赋值别名,避免因为两个表字段名称相同而注入到对应对象名称冲突-->
- select m.id m_id,m.telnumber,u.id u_id,u.name,u.pass from t_mobile m,t_user u where m.userid = u.id and m.id = #{id}
- </select>
- </mapper>