首先,我不是在谈论Marshaller#Listener .
我说的是那些 class defined
事件回调。
谁能告诉我boolean beforeMarshal(Marshaller)
方法应该返回什么?
/**
* Where is apidocs for this method?
* What should I return for this?
*/
boolean beforeMarshal(Marshaller marshaller);
我的意思是,无论如何,使用此方法将 JPA 的 Long @Id 转换为 JAXB 的 String @XmlID
使用 JAXB-RI 并且不使用 MOXy.
[编辑]
void
版本似乎可以工作。这只是文档问题吗?
最佳答案
简答题
boolean
返回类型是文档错误。返回类型应为 void
。
长答案
I mean, anyway, to use this method for converting JPA's Long @Id to JAXB's String @XmlID
你可以使用 EclipseLink JAXB (MOXy)因为它没有限制用 @XmlID
注释的字段/属性是 String
类型。
with JAXB-RI and without MOXy.
您可以使用 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);
}
}
B
@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;
}
一个
package forum9629948;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class A {
private B b;
private C c;
}
C
package forum9629948;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)public class C {
@XmlAttribute
@XmlIDREF
private B b;
}
演示
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);
}
}
输入/输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
<b id="123"/>
<c b="123"/>
</a>
关于java - JAXB `beforeMarshal(Marshaller)` 方法应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9629948/