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

Grails中如何为hasMany关联字段设置XmlAttribute相关注解

核心问题原因

Grails的static hasMany仅用于GORM关联声明,对应的集合字段是运行时动态注入到类中的,JAXB默认扫描类编译时已存在的显式字段/属性,因此直接在hasMany块内加注解不会生效。


可行解决方案

方案1:显式声明集合字段(最推荐)

Grails GORM会自动识别你显式声明的集合字段和hasMany的关联映射,不需要改动原有关联逻辑,同时JAXB可以正常识别该字段上的注解:

import javax.xml.bind.annotation.XmlAccessType
import javax.xml.bind.annotation.XmlAccessorType
import javax.xml.bind.annotation.XmlAttribute
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlType

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AuditSourceIdentificationType", propOrder = [
        "auditSourceTypeCodes" // 注意这里要和实际字段名一致,原代码的单数写法是错误的
])
class AuditSourceIdentificationType {

    // 显式声明集合字段,添加JAXB注解
    @XmlElement(name = "AuditSourceTypeCode")
    List<CodedValue> auditSourceTypeCodes

    static hasMany = [
            auditSourceTypeCodes: CodedValue
    ]

    @XmlAttribute(name = "AuditEnterpriseSiteID")
    String auditEnterpriseSiteID

    @XmlAttribute(name = "AuditSourceID", required = true)
    String auditSourceID
}

方案2:在Getter方法上加注解

如果你不想显式声明字段,可以将@XmlAccessorType修改为XmlAccessType.PROPERTY,然后显式实现对应的Getter方法添加注解:

@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(name = "AuditSourceIdentificationType", propOrder = [
        "auditSourceTypeCodes"
])
class AuditSourceIdentificationType {

    static hasMany = [
            auditSourceTypeCodes: CodedValue
    ]

    @XmlElement(name = "AuditSourceTypeCode")
    List<CodedValue> getAuditSourceTypeCodes() {
        return auditSourceTypeCodes
    }

    // 其余属性保持原有写法
}

特殊场景说明

如果你确实需要将集合内容序列化为XML属性(而非XML子节点),由于XML属性只能是字符串值,你需要额外配置@XmlJavaTypeAdapter,自定义适配器将集合转换为符合要求的字符串格式,示例如下:

  1. 先定义适配器类:
import javax.xml.bind.annotation.adapters.XmlAdapter

class CodedValueListAdapter extends XmlAdapter<String, List<CodedValue>> {
    @Override
    List<CodedValue> unmarshal(String v) throws Exception {
        // 实现字符串转回集合的逻辑
        return v.split(",").collect { new CodedValue(value: it) }
    }

    @Override
    String marshal(List<CodedValue> v) throws Exception {
        // 实现集合转字符串的逻辑
        return v*.value.join(",")
    }
}
  1. 在集合字段上添加对应注解:
@XmlAttribute(name = "AuditSourceTypeCodes")
@XmlJavaTypeAdapter(CodedValueListAdapter.class)
List<CodedValue> auditSourceTypeCodes

内容的提问来源于stack exchange,提问作者Jim Gough

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:09:05