在企业级Java开发领域,多层架构模式凭借其清晰的职责划分与强大的可维护性,成为构建复杂业务系统的主流选择。本文以通用业务数据查询接口为例,结合MyBatis框架的核心特性,深入解析Controller、Service、ServiceImpl和Mapper层的完整代码逻辑与运行机制,重点剖析MyBatis中<collection>标签在处理复杂数据关联时的关键作用。

一、多层架构各层功能概述

多层架构通过将系统按功能分层,使各层各司其职,有效降低模块间的耦合度:

  • Controller层:作为系统与外部交互的入口,负责接收和处理用户请求,校验参数合法性,将请求参数传递给Service层处理,并将Service层返回的结果封装成标准响应格式(如JSON)返回给客户端。
  • Service层:专注于业务逻辑的抽象与封装,定义业务接口,不涉及具体的数据访问操作,为上层提供统一、稳定的业务操作入口,确保业务规则的一致性。
  • ServiceImpl层:是Service接口的具体实现层,在这一层调用Mapper层完成数据库的增删改查操作,并对数据进行业务逻辑处理,如数据校验、转换等,是连接业务逻辑与数据访问的桥梁。
  • Mapper层:基于MyBatis框架,专注于数据库操作。通过XML映射文件或注解定义SQL语句,并利用ResultMap实现数据库字段与Java实体类属性的映射,其中<collection>标签专门用于处理一对多的数据关联关系。

二、各层代码实现与解析

(一)Controller层:请求处理与响应封装

// Controller层
package com.example.general.controller;

import com.example.general.domain.MainEntity;
import com.example.general.service.IMainEntityService;
import com.example.common.core.controller.BaseController;
import com.example.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/general/data")
public class MainEntityController extends BaseController {

    @Autowired
    private IMainEntityService mainEntityService;

    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        MainEntity entity = mainEntityService.getById(id);
        return AjaxResult.success(entity);
    }

    @GetMapping("/list")
    public AjaxResult list() {
        return AjaxResult.success(mainEntityService.list());
    }
}

Controller层的MainEntityController类通过@RestController注解声明为RESTful风格的控制器,@RequestMapping("/general/data")定义请求路径前缀。getInfo方法接收路径参数id,调用mainEntityServicegetById方法查询单条数据;list方法调用mainEntityServicelist方法获取全部数据,最终将结果封装成AjaxResult返回给客户端。

(二)Service层:业务接口定义

// Service层接口
package com.example.general.service;

import com.example.general.domain.MainEntity;

import java.util.List;

public interface IMainEntityService {

    MainEntity getById(Long id);

    List<MainEntity> list();
}

Service层的IMainEntityService接口定义了getByIdlist两个抽象方法,分别用于根据ID查询单条数据和获取全部数据。该接口仅关注业务逻辑的定义,不涉及具体实现细节,为业务的扩展和维护提供了清晰的边界。

(三)ServiceImpl层:业务逻辑实现

// ServiceImpl层
package com.example.general.service.impl;

import com.example.general.domain.MainEntity;
import com.example.general.mapper.MainEntityMapper;
import com.example.general.service.IMainEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MainEntityServiceImpl implements IMainEntityService {

    @Autowired
    private MainEntityMapper mainEntityMapper;

    @Override
    public MainEntity getById(Long id) {
        return mainEntityMapper.selectById(id);
    }

    @Override
    public List<MainEntity> list() {
        return mainEntityMapper.selectList();
    }
}

ServiceImpl层的MainEntityServiceImpl类通过@Service注解声明为服务类,实现IMainEntityService接口。在方法实现中,调用mainEntityMapper的对应方法,将数据查询操作委托给Mapper层,同时可在此层添加事务管理、数据校验等业务逻辑。

(四)Mapper层:数据访问与映射配置

// Mapper接口
package com.example.general.mapper;
import com.example.general.domain.MainEntity;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface MainEntityMapper {

    MainEntity selectById(Long id);
    List<MainEntity> selectList();
}
<?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.example.general.mapper.MainEntityMapper">

    <resultMap type="MainEntity" id="BaseResultMap">
        <!-- 主表字段映射 -->
        <id column="main_entity_id" property="id" jdbcType="BIGINT"/>
        <result column="main_field_a" property="fieldA" jdbcType="VARCHAR"/>
        <result column="main_field_b" property="fieldB" jdbcType="VARCHAR"/>

        <!-- 重点:一对多关联映射,使用<collection>标签 -->
        <collection
            property="relatedList"
            ofType="RelatedEntity"
            columnPrefix="r."
        >
            <id column="related_id" property="id" jdbcType="BIGINT"/>
            <result column="related_name" property="name" jdbcType="VARCHAR"/>
            <result column="related_value" property="value" jdbcType="VARCHAR"/>
        </collection>
    </resultMap>

    <select id="selectById" resultMap="BaseResultMap">
        SELECT
            m.main_entity_id,
            m.main_field_a,
            m.main_field_b,
            r.related_id,
            r.related_name,
            r.related_value
        FROM main_entity m
        LEFT JOIN related_entity r
            ON m.main_entity_id = r.main_entity_id
        WHERE m.main_entity_id = #{id,jdbcType=BIGINT}
    </select>

    <select id="selectList" resultMap="BaseResultMap">
        SELECT
            m.main_entity_id,
            m.main_field_a,
            m.main_field_b,
            r.related_id,
            r.related_name,
            r.related_value
        FROM main_entity m
        LEFT JOIN related_entity r
            ON m.main_entity_id = r.main_entity_id
    </select>
</mapper>

Mapper层包含MainEntityMapper接口和XML映射文件。接口通过@Mapper注解被Spring容器管理,定义数据查询方法。XML映射文件中,resultMap标签定义数据库字段与Java实体类属性的映射关系,<collection>标签用于处理主实体与关联实体的一对多关系。它将主表与从表JOIN后的结果集,按主表主键分组,自动将从表记录映射到主实体对象的relatedList集合属性中。

例如,当查询主实体数据时,若一条主实体记录关联多条从实体记录,MyBatis会将这些从实体记录自动封装到relatedList中,无需开发者手动编写复杂的分组和集合填充代码,大大提高了开发效率和代码的可读性。

(五)实体类

package com.example.general.domain;

import java.util.List;

public class MainEntity {
    private Long id; // 主实体ID
    private String fieldA; // 主实体字段A
    private String fieldB; // 主实体字段B
    private Double numericField; // 主实体数值型字段
    private List<RelatedEntity> relatedList; // 关联实体列表

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFieldA() {
        return fieldA;
    }

    public void setFieldA(String fieldA) {
        this.fieldA = fieldA;
    }

    public String getFieldB() {
        return fieldB;
    }

    public void setFieldB(String fieldB) {
        this.fieldB = fieldB;
    }

    public Double getNumericField() {
        return numericField;
    }

    public void setNumericField(Double numericField) {
        this.numericField = numericField;
    }

    public List<RelatedEntity> getRelatedList() {
        return relatedList;
    }

    public void setRelatedList(List<RelatedEntity> relatedList) {
        this.relatedList = relatedList;
    }

    // 内部类:关联实体
    public static class RelatedEntity {
        private Long relatedId; // 关联实体ID
        private String relatedName; // 关联实体名称
        private String relatedPath; // 关联资源路径(如文件路径、URL等)

        // Getters and Setters
        public Long getRelatedId() {
            return relatedId;
        }

        public void setRelatedId(Long relatedId) {
            this.relatedId = relatedId;
        }

        public String getRelatedName() {
            return relatedName;
        }

        public void setRelatedName(String relatedName) {
            this.relatedName = relatedName;
        }

        public String getRelatedPath() {
            return relatedPath;
        }

        public void setRelatedPath(String relatedPath) {
            this.relatedPath = relatedPath;
        }
    }
}

(六)响应示例

{
  "code": 200,
  "msg": "操作成功",
  "data": [
    {
      "mainEntityId": 1,          // 主实体ID
      "mainFieldA": "示例值A1",    // 主实体字段A
      "mainFieldB": "示例值B1",    // 主实体字段B
      "relatedList": [            // 关联对象列表(一对多关系)
        {
          "relatedId": 101,       // 关联对象ID
          "relatedName": "附件-1", // 关联对象名称
          "relatedPath": "/path/to/resource/1" // 关联资源路径
        }
      ]
    },
    {
      "mainEntityId": 2,
      "mainFieldA": "示例值A2",
      "mainFieldB": "示例值B2",
      "relatedList": [] // 无关联数据时返回空数组
    }
  ]
}