SpringBoot+Mybatis实现多表联查

684 阅读1分钟

参考博文:余情呀

创建两张表user和account表

显然这两张表是一对多的关系

user表: image.png account表: image.png -- 用户实体类

public class User {
    private Interge id;
    private String username;
    private Date birthday;
    private String address;
    private String sex;
    //记得创建get、set方法
}

-- 账户实体类

public class Account {
    private Integer id;
    private Integer uid;
    private Double money;
    //记得创建get、set方法
}

方法一,通过创建子类的方式查询

例如这边创建一个UserAccount类

public class UserAccount extends User {
    private Double money;
    
    public Double getMoney() {
        return money;
    }
    
    public void setMoney(Double money) {
        this.money = money;
    }
}

-- 创建对应的UserDao

public interface UserDao {
    //查询所有User以及其账户余额
    List<UserAccount> selectUserAccountList();
}

-- 创建对应的UserService(这里省略代码)

-- 创建对应的UserServiceImpl实现类

public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserDao userDao;
    
    @Override
    public List<UserAccout> getUserAccountList() {
        List<UserAccount> users = userDao.selectUserAccountList();
        return users;
    }
}

-- 创建Controller层

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/useraccountlist")
    Map<String,Object> modelMap = new HashMap<>();
    List<UserAccount> userAccount = userService.getUserAccountList();
    modelMap.put("userAccountList",userAccountList);
    return modelMap;
}

-- xml编写SQL语句(看SQL语句很容易看出来这个就是最简单的联查,只不过新构建出一个类用于数据展示而已)

<select id="selectUserAccountList" resultType="UserAccount">
        select u.*,a.money from user u,account a where u.id = a.UID
</select>

-- 结果展示

image.png

方法二,建立实体类关系方式进行查询

需求:查询所有账户及其所属用户的所有基础用户信息

-- 修改Account实体类,在其中加上一个user属性,并且生成对应的get、set方法

-- xml编写映射实体类

<mapper namespace="AccountDao">
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="uid"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <association property="user" column="uid" javaType="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>
        </association>
    </resultMap>    
    s
    <select id="selectAccountUserList" resultMap="accountUserMap">
        select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id = a.uid;
    </select>
</mapper>