JAXB应该从`beforeMarshal(Marshaller)方法返回什么?

Jin*_*won 7 java jaxb

首先,我不是在谈论Marshaller#Listener.我在谈论那些class defined事件回调.

谁能告诉我应该从boolean beforeMarshal(Marshaller)方法中返回什么?

/**
 * Where is apidocs for this method?
 * What should I return for this?
 */
boolean beforeMarshal(Marshaller marshaller);
Run Code Online (Sandbox Code Playgroud)

我的意思是,无论如何,用于转换这种方法JPA's Long @Id to JAXB's String @XmlID 与JAXB-RI无莫西.

[编辑]一个void版本似乎工作.这只是一个文档问题吗?

bdo*_*han 6

简答

boolean返回类型是一个文档的错误.返回类型应该是void.

答案很长

无论如何,我的意思是使用此方法将JPA的Long @Id转换为JAXB的String @XmlID

您可以使用EclipseLink JAXB(MOXy),因为它没有带有注释@XmlID类型的字段/属性的限制String.

使用JAXB-RI且没有MOXy.

您可以使用a XmlAdapter来映射支持您的用例:

IDAdapter

XmlAdapter会将Long值转换为String值以满足@XmlID注释的要求.

package forum9629948;

import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class IDAdapter extends XmlAdapter<String, Long> {

    @Override
    public Long unmarshal(String string) throws Exception {
        return DatatypeConverter.parseLong(string);
    }

    @Override
    public String marshal(Long value) throws Exception {
        return DatatypeConverter.printLong(value);
    }

}
Run Code Online (Sandbox Code Playgroud)

@XmlJavaTypeAdapter注释用于指定XmlAdapter:

package forum9629948;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlAccessorType(XmlAccessType.FIELD)
public class B {

    @XmlAttribute
    @XmlID
    @XmlJavaTypeAdapter(IDAdapter.class)
    private Long id;

}
Run Code Online (Sandbox Code Playgroud)

一个

package forum9629948;

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class A {

    private B b;
    private C c;

}
Run Code Online (Sandbox Code Playgroud)

C

package forum9629948;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)public class C {

    @XmlAttribute
    @XmlIDREF
    private B b;

}
Run Code Online (Sandbox Code Playgroud)

演示

package forum9629948;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(A.class);

        File xml = new File("src/forum9629948/input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        A a = (A) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(a, System.out);
    }

}
Run Code Online (Sandbox Code Playgroud)

输入输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
    <b id="123"/>
    <c b="123"/>
</a>
Run Code Online (Sandbox Code Playgroud)