You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将子字段添加至parentDTO?JDL与代码实现咨询

JDL配置及DTO代码实现方案

正确JDL配置

先修正实体命名(将Regions改为单数Region,符合领域模型命名规范),通过JDL的关联语法建立一对多关系,同时指定DTO生成规则:

entity Country {
  name String
}

entity Region {
  name String
  population Integer
}

// 定义一对多关联:一个国家对应多个区域
relationship OneToMany {
  Country to Region { regions }
}

// 配置Country的DTO,包含区域列表
dto Country with mapstruct {
  name String
  regions List<RegionDTO>
}

// 配置Region的DTO
dto Region with mapstruct {
  name String
  population Integer
}

代码实现说明

  1. 实体类自动生成:JDL会自动为Country实体添加List<Region> regions字段,并生成JPA关联注解(@OneToMany(mappedBy = "country"));同时为Region实体添加Country country关联字段及@ManyToOne注解,无需手动编写关联逻辑。
  2. DTO类自动生成:生成的CountryDTO包含id、name和List<RegionDTO> regions字段;RegionDTO包含id、name、population字段,完全匹配期望的JSON结构。
  3. 映射器自动生成:基于MapStruct的映射器会自动处理实体到DTO的转换,包括集合类型的映射,无需手动编写循环转换代码。

验证输出

生成的CountryDTO序列化为JSON后,结构如下(与期望一致):

{"id": 1,"name": "USA","regions": [{"id": 1,"name": "florida","population":150000},{"id": 2,"name": "newyork","population":12}]}

内容的提问来源于stack exchange,提问作者Troo TrIIs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:09:30