mybatisplus 一对多配置

旧街凉风 提交于 2020-04-17 20:23:07

1:数据库表

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `t_user_id` bigint(255) NOT NULL AUTO_INCREMENT,
  `t_user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  `t_user_age` smallint(255) NULL DEFAULT NULL,
  PRIMARY KEY (`t_user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for t_user_address
-- ----------------------------
DROP TABLE IF EXISTS `t_user_address`;
CREATE TABLE `t_user_address`  (
  `t_address_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `t_user_id` bigint(255) NULL DEFAULT NULL,
  `t_address_desc` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  PRIMARY KEY (`t_address_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;

2:实体类

(1)User

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "t_user_id", type = IdType.AUTO)
    private Long tUserId;

    private String tUserName;

    private Integer tUserAge;

    @TableField(exist = false)//表示该属性不为数据库表字段,但又是必须使用的
    private List<Address> userAddressList;
}

 

(2)Address

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_user_address")
public class Address {
    private static final long serialVersionUID = 1L;

    @TableId(value = "t_address_id", type = IdType.AUTO)
    private Long tAddressId;

    private String tUserId;

    private String tAddressDesc;
}

3:Mapper

(1)UserMapper

public interface UserMapper extends BaseMapper<User> {
    List<User> getUserList(Page<User> page);
}

(2)UserMapper.xml

<?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="com.wzh.springbootmp.mapper.UserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.wzh.springbootmp.entity.User">
        <id column="t_user_id" property="tUserId" />
        <result column="t_user_name" property="tUserName" />
        <result column="t_user_age" property="tUserAge" />

        <collection property="userAddressList" column="{t_user_id=t_user_id}" select="getUserAddressById"/>
    </resultMap>

    <!--根据userID查询地址信息-->
    <select id="getUserAddressById" resultType="com.wzh.springbootmp.entity.Address">
        select t_user_id,t_address_id,t_address_desc
        from t_user_address
        where t_user_id=#{t_user_id}
    </select>

    <!--获取用户列表信息-->
    <select id="getUserList" resultMap="BaseResultMap">
        select t_user_id,t_user_name,t_user_age
        from t_user
    </select>
</mapper>

4:Service

(1)IUserService

public interface IUserService extends IService<User> {
    Page<User> getUserList(Page<User> page);
}

 

(2)UserServiceImpl

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Page<User> getUserList(Page<User> page) {
        return page.setRecords(this.baseMapper.getUserList(page));
    }
}

 

5:UserController

@RestController
@AllArgsConstructor
public class UserController {

    private IUserService userService;

    @GetMapping("/users/{page}/{size}")
    public Map<String,Object> getUserList(@PathVariable Integer page, @PathVariable Integer size){
        Map<String, Object> map = new HashMap<>();

        Page<User> pageUser = new Page<>(page, size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        IPage<User> pages = userService.page(pageUser, queryWrapper);

        if (pages.getRecords().size() == 0) {
            map.put("code", -1);
        } else {
            map.put("code", 1);
            map.put("data", pages);
        }
        return map;
    }

    @GetMapping("/userAddressList/{page}/{size}")
    public Map<String, Object> getUserAddressList(@PathVariable Integer page, @PathVariable Integer size) {
        Map<String, Object> map = new HashMap<>();
        Page<User> userAddressPage = userService.getUserList(new Page<>(page, size));

        if (userAddressPage.getRecords().size() == 0) {
            map.put("code", 1);
        } else {
            map.put("code", 0);
            map.put("data", userAddressPage);
        }

        return map;
    }

}

6:测试结果

{
  "code": 0,
  "data": {
    "records": [
      {
        "userAddressList": [
          {
            "taddressDesc": "徐州路",
            "taddressId": 1,
            "tuserId": "1"
          },
          {
            "taddressDesc": "东莞路",
            "taddressId": 2,
            "tuserId": "1"
          }
        ],
        "tuserAge": 20,
        "tuserId": 1,
        "tuserName": "张三"
      },
      {
        "userAddressList": [
          {
            "taddressDesc": "抚顺路",
            "taddressId": 3,
            "tuserId": "2"
          }
        ],
        "tuserAge": 30,
        "tuserId": 2,
        "tuserName": "李四"
      }
    ],
    "total": 2,
    "size": 10,
    "current": 1,
    "pages": 1
  }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!