栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring boot2基于Mybatis实现多表关联查询

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring boot2基于Mybatis实现多表关联查询

模拟业务关系:

一个用户user有对应的一个公司company,每个用户有多个账户account。

spring boot 2的环境搭建见上文:spring boot 2整合mybatis

一、mysql创表和模拟数据sql

CREATE TABLE IF NOT EXISTS `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL,
 `company_id` int(11) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `company` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `account` (
 `id` int(11) NOT NULL AUTO_INCREMENT, 
 `name` varchar(200) NOT NULL,
 `user_id` int(11) NOT NULL, 
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO
  `user`
VALUES
  (1, 'aa', 1),
  (2, 'bb', 2);

INSERT INTO
  `company`
VALUES
  (1, 'xx公司'),
  (2, 'yy公司');

INSERT INTO
  `account`
VALUES
  (1, '中行', 1),
  (2, '工行', 1),
  (3, '中行', 2);

二、创建实体

public class User {    
  private Integer id;
  private String name;
  private Company company;
  private List accounts;  
  //getter/setter 这里省略...
}

public class Company {
  private Integer id;
  private String companyName;
    //getter/setter 这里省略...
}

public class Account {
  private Integer id;
  private String accountName;
  //getter/setter 这里省略...

}

三、开发Mapper

方法一:使用注解

1、AccountMapper.java

package com.example.demo.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import com.example.demo.entity.Account;
public interface AccountMapper {
  
  @Select("SELECT * FROM `account` WHERe user_id = #{userId}")
  @Results({
    @Result(property = "accountName", column = "name")
  })
  List getAccountByUserId(Long userId);
}

2、CompanyMapper.java

package com.example.demo.mapper;

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.example.demo.entity.Company;

public interface CompanyMapper {
  
  @Select("SELECT * FROM company WHERe id = #{id}")
  @Results({
    @Result(property = "companyName", column = "name")
  })
  Company getCompanyById(Long id);
}

3、UserMapper.java

package com.example.demo.mapper;

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Many;

import com.example.demo.entity.User;

public interface UserMapper {
  
  
  @Select("SELECT * FROM user WHERe id = #{id}")
  @Results({
    @Result(property = "company", column = "company_id", one = @One(select = "com.example.demo.mapper.CompanyMapper.getCompanyById"))    
  })
  User getUserWithCompany(Long id);
  
  
  @Select("SELECT * FROM user WHERe id = #{id}")
  @Results({ 
    @Result(property = "id", column = "id"),//加此行,否则id值为空
    @Result(property = "accounts", column = "id", many = @Many(select = "com.example.demo.mapper.AccountMapper.getAccountByUserId"))
  })
  User getUserWithAccount(Long id);
  
  
  @Select("SELECT * FROM user")
  @Results({
    @Result(property = "id", column = "id"),
    @Result(property = "company", column = "company_id", one = @One(select = "com.example.demo.mapper.CompanyMapper.getCompanyById")),
    @Result(property = "accounts", column = "id", many = @Many(select = "com.example.demo.mapper.AccountMapper.getAccountByUserId"))
  })
  List getAll();  
}

方法二:使用XML

参考上文spring boot 2整合mybatis配置application.properties和mybatis-config.xml等后,
以上面的getAll()方法为例,UserMapper.xml配置如下:




  
    
      
    
    
      
            
    
    
    
      
            
        
   

  

四、控制层

package com.example.demo.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;

@RestController
public class UserController {
  @Autowired
  private UserMapper userMapper;
  
  //请求例子:http://localhost:9001/getUserWithCompany/1
  
  @RequestMapping("/getUserWithCompany/{id}")
  public User getUserWithCompany(@PathVariable("id") Long id) {
    User user = userMapper.getUserWithCompany(id);
    return user;
  }
  

  //请求例子:http://localhost:9001/getUserWithAccount/1
  
  @RequestMapping("/getUserWithAccount/{id}")
  public User getUserWithAccount(@PathVariable("id") Long id) {
    User user = userMapper.getUserWithAccount(id);
    return user;
  }
  

  //请求例子:http://localhost:9001/getUserWithAccount/1
  
  @RequestMapping("/getUsers")
  public List getUsers() {
    List users=userMapper.getAll();
    return users;
  }  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/134341.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号