2

我正在使用 EclipseLink JPA 和 JAXB (MOXy) 将 JPA 实体转换为 XML。对于正常的一对多操作,系统可以正常工作,但如果这种关系是双向的,并且其中一个实体具有复合 ID,则使用 java.util.Map 类,系统会抛出异常。

关系是:

表格1:

Fields: id, col1. 
Primary Key: id

表2:

Fields: id, table1_id, col1
Primary Key: (id, table1_id)

我的课程:

类表1:

@Entity
@Table(name = "table1")
@XmlRootElement
public class Table1 implements Serializable {

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "table1")
    @MapKey(name = "table2PK")
    @XmlElement    
    @XmlInverseReference(mappedBy="table1")
    private Map<Table2PK, Table2> table2;

    @XmlElementWrapper(name="table2s")
    public Map<Table2PK, Table2> getTable2() {
        return table2;
    }

    // Gettters and setters methods
}

类表2:

@Entity
@Table(name = "table2")
@XmlRootElement
public class Table2 implements Serializable {

    @EmbeddedId
    protected Table2PK table2PK;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "table1_id", insertable = false, unique = false, nullable = false, updatable = false)
    private Table1 table1;

    // Gettters and setters methods
}

类 Table2PK:

@Embeddable
public class Table2PK implements Serializable {

    @Basic(optional = false)
    @Column(name = "id")
    private int id;
    @Basic(optional = false)
    @Column(name = "table1_id")
    private int table1Id;

    // Gettters and setters methods
}

JPA 工作正常,但 JAXB 编组和解组操作使用以下代码:

JAXBContext jc1 = JAXBContext.newInstance(Table1.class);

Marshaller marshaller = jc2.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(ts, System.out);

抛出 javax.xml.bind.JAXBException。

消息是:

Exception [EclipseLink-110] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Descriptor is missing for class [java.util.Map].
Mapping: org.eclipse.persistence.oxm.mappings.XMLInverseReferenceMapping[table2]
Descriptor: XMLDescriptor(org.jbiowhpersistence.datasets.gene.gene.entities.Table1 --> [DatabaseTable(table1)])

Exception [EclipseLink-110] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Descriptor is missing for class [java.util.Map].
Mapping: org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping[table2]
Descriptor: XMLDescriptor(org.jbiowhpersistence.datasets.gene.gene.entities.Table1 --> [DatabaseTable(table1)])

我的班级定义有什么问题?预先感谢和最好的问候。

4

2 回答 2

1

EclipseLink JAXB (MOXy)不支持@XmlInverseReference类型的字段/属性java.util.Map。不支持这一点的部分原因是避免指定反向引用何时适用于:仅键、仅值或键和值两者的复杂性。

于 2013-11-13T17:24:46.173 回答
0

使用 JAXB 无法映射 Map。您需要创建一个可映射的等效类。然后创建一个 XMlAdapter 以将不可映射的对象转换为可映射的对象。

例如:

class MapType{
    public List<MapEntryType> mapEntries = new ArrayList<MapEntryType>();
}

class MapEntryType {     
         @XmlAttribute   public Integer key;       
         @XmlValue   public String value;   
}

您可以在此链接上找到如何创建 XMLAdapter

希望能帮助到你。

于 2013-11-13T08:43:39.397 回答