JAXB:将单独的日期和时间元素映射到一个属性

发布于 2024-09-15 18:38:02 字数 3011 浏览 3 评论 0原文

我正在使用如下所示的 XML 结构:

<ROOT>
    <ELEM_A>
        <A_DATE>20100825</A_DATE>
        <A_TIME>141500</A_TIME>
        <!-- other elements, maybe also other or date/time combinations -->
        <STRING>ABC</STRING>
    <ELEM_A>
    <ELEM_B>
        <B_DATE>20100825</B_DATE>
        <B_TIME>153000</B_TIME>
        <NUM>123</NUM>
        <C_DATE>20100825</C_DATE>
        <C_TIME>154500</C_TIME>
    </ELEM_B>
</ROOT>

我想将日期和时间映射到 bean 中的单个 DateCalendar 属性。使用 jaxb 注释可以吗? javax.xml.bind.annotation.adapters.XmlAdapter 类看起来可能能够做到这一点,但我必须承认我并不完全理解它的 javadoc。

解决方法是为日期和时间字符串创建额外的设置器,以在 Calendar 属性中设置相应的值,如下所示:

private Calendar calendar;

public void setDate(String date) {
    if (calendar == null) {
        calendar = new GregorianCalendar();
    }
    calendar.set(YEAR, Integer.parseIn(date.substring(0, 4)));
    calendar.set(MONTH, Integer.parseIn(date.substring(4, 6))-1);
    calendar.set(DAY_OF_MONTH, Integer.parseIn(date.substring(6, 8)));
}

// Similar code for setTime

问题(除了附加代码之外)是我不能总是保证日期设置在时间值之前,但我想不出一个具体的例子,这可能会给出磨损的结果。

任何基于注释的解决方案的示例或上述代码的改进/反示例都值得赞赏。

编辑:我采用了Blaise Doughan给出的第二个答案,但修改了他的 DateAttributeTransformer更加灵活,并且不期望字段名称包含字符串“DATE”。字段名称取自字段上的 XmlWriterTransformer 注释:

@Override
public Object buildAttributeValue(Record record, Object instance, Session session) {
    try {
        String dateString = null;
        String timeString = null;

        String dateFieldName = null;
        String timeFieldName = null;
        // TODO: Proper Exception handling
        try {
            XmlWriteTransformers wts = instance.getClass().getDeclaredField(mapping.getAttributeName()).getAnnotation(XmlWriteTransformers.class);
            for (XmlWriteTransformer wt : wts.value()) {
                String fieldName = wt.xpath();
                if (wt.transformerClass() == DateFieldTransformer.class) {
                    dateFieldName = fieldName;
                } else {
                    timeFieldName = fieldName;
                }
            }
        } catch (NoSuchFieldException ex) {
            throw new RuntimeException(ex);
        } catch (SecurityException ex) {
            throw new RuntimeException(ex);
        }

        for(DatabaseField field : mapping.getFields()) {
            XMLField xfield = (XMLField)field;
            if(xfield.getXPath().equals(dateFieldName)) {
                dateString = (String) record.get(field);
            } else {
                timeString = (String) record.get(field);
            }
        }
        return yyyyMMddHHmmss.parseObject(dateString + timeString);
    } catch(ParseException e) {
        throw new RuntimeException(e);
    }
}

I'm working with a XML structure that looks like this:

<ROOT>
    <ELEM_A>
        <A_DATE>20100825</A_DATE>
        <A_TIME>141500</A_TIME>
        <!-- other elements, maybe also other or date/time combinations -->
        <STRING>ABC</STRING>
    <ELEM_A>
    <ELEM_B>
        <B_DATE>20100825</B_DATE>
        <B_TIME>153000</B_TIME>
        <NUM>123</NUM>
        <C_DATE>20100825</C_DATE>
        <C_TIME>154500</C_TIME>
    </ELEM_B>
</ROOT>

And I want to map date and time to a single Date or Calendar property in my bean. Is this possible using jaxb annotations? The class javax.xml.bind.annotation.adapters.XmlAdapter looks like it might be able to do this, but I have to admit I don't fully understand its javadoc.

A workaround would be to create additional setters for the date and time strings that set the corresponding values in a Calendar property like this:

private Calendar calendar;

public void setDate(String date) {
    if (calendar == null) {
        calendar = new GregorianCalendar();
    }
    calendar.set(YEAR, Integer.parseIn(date.substring(0, 4)));
    calendar.set(MONTH, Integer.parseIn(date.substring(4, 6))-1);
    calendar.set(DAY_OF_MONTH, Integer.parseIn(date.substring(6, 8)));
}

// Similar code for setTime

The problem (apart from the additional code) is that I can't always guarantee that the date is set before the time value, but I can't think of a specific example where this might give worng results.

Any examples for an annotation based solution or improvements / counter examples for the code above are appreciated.

Edit: I went with the second answer given by Blaise Doughan, but modified his DateAttributeTransformer to be more flexible and not expect the field name to contain the string "DATE". The field names are taken from the XmlWriterTransformer annotations on the field:

@Override
public Object buildAttributeValue(Record record, Object instance, Session session) {
    try {
        String dateString = null;
        String timeString = null;

        String dateFieldName = null;
        String timeFieldName = null;
        // TODO: Proper Exception handling
        try {
            XmlWriteTransformers wts = instance.getClass().getDeclaredField(mapping.getAttributeName()).getAnnotation(XmlWriteTransformers.class);
            for (XmlWriteTransformer wt : wts.value()) {
                String fieldName = wt.xpath();
                if (wt.transformerClass() == DateFieldTransformer.class) {
                    dateFieldName = fieldName;
                } else {
                    timeFieldName = fieldName;
                }
            }
        } catch (NoSuchFieldException ex) {
            throw new RuntimeException(ex);
        } catch (SecurityException ex) {
            throw new RuntimeException(ex);
        }

        for(DatabaseField field : mapping.getFields()) {
            XMLField xfield = (XMLField)field;
            if(xfield.getXPath().equals(dateFieldName)) {
                dateString = (String) record.get(field);
            } else {
                timeString = (String) record.get(field);
            }
        }
        return yyyyMMddHHmmss.parseObject(dateString + timeString);
    } catch(ParseException e) {
        throw new RuntimeException(e);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你的他你的她 2024-09-22 18:38:02

XmlAdapter 是正确的方法:

具有 Date 属性的类

import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name="ROOT")
public class Root {

    private Date date;

    @XmlElement(name="ELEM")
    @XmlJavaTypeAdapter(DateAdapter.class)
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

}

XmlAdapter 的实现

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter<AdaptedDate, Date> {

    private SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
    private SimpleDateFormat HHmmss = new SimpleDateFormat("HHmmss");
    private SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");

    @Override
    public Date unmarshal(AdaptedDate v) throws Exception {
        String dateString = v.getDate() + v.getTime();
        return yyyyMMddHHmmss.parse(dateString);
    }

    @Override
    public AdaptedDate marshal(Date v) throws Exception {
        AdaptedDate adaptedDate = new AdaptedDate();
        adaptedDate.setDate(yyyyMMdd.format(v));
        adaptedDate.setTime(HHmmss.format(v));
        return adaptedDate;
    }

}

适配的 Date 对象

import javax.xml.bind.annotation.XmlElement;

public class AdaptedDate {

    private String date;
    private String time;

    @XmlElement(name="DATE")
    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @XmlElement(name="TIME")
    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

}

示例程序

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

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

        File xml = new File("input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(xml);

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

XML 文档

<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
    <ELEM>
        <DATE>20100825</DATE>
        <TIME>141500</TIME>
    </ELEM>
</ROOT> 

有关详细信息,请参阅:

XmlAdapter is the right approach:

Class with Date property

import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name="ROOT")
public class Root {

    private Date date;

    @XmlElement(name="ELEM")
    @XmlJavaTypeAdapter(DateAdapter.class)
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

}

The implementation of XmlAdapter

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter<AdaptedDate, Date> {

    private SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
    private SimpleDateFormat HHmmss = new SimpleDateFormat("HHmmss");
    private SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");

    @Override
    public Date unmarshal(AdaptedDate v) throws Exception {
        String dateString = v.getDate() + v.getTime();
        return yyyyMMddHHmmss.parse(dateString);
    }

    @Override
    public AdaptedDate marshal(Date v) throws Exception {
        AdaptedDate adaptedDate = new AdaptedDate();
        adaptedDate.setDate(yyyyMMdd.format(v));
        adaptedDate.setTime(HHmmss.format(v));
        return adaptedDate;
    }

}

The adapted Date object

import javax.xml.bind.annotation.XmlElement;

public class AdaptedDate {

    private String date;
    private String time;

    @XmlElement(name="DATE")
    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @XmlElement(name="TIME")
    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

}

Sample program

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

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

        File xml = new File("input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(xml);

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

XML Document

<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
    <ELEM>
        <DATE>20100825</DATE>
        <TIME>141500</TIME>
    </ELEM>
</ROOT> 

For more information see:

北方。的韩爷 2024-09-22 18:38:02

您可以使用 MOXy JAXB 实现(我是技术主管),而不是使用 JAXB RI (Metro)。它有一些扩展,可以使映射此场景变得相当容易。

jaxb.properties

要使用 MOXy 作为 JAXB 实现,您需要在与模型类相同的包中添加一个名为 jaxb.properties 的文件,其中包含以下条目:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Root

import javax.xml.bind.annotation.*;

@XmlRootElement(name="ROOT")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement(name="ELEM_A")
    private ElemA elemA;

    @XmlElement(name="ELEM_B")
    private ElemB elemB;

}

ElemA

我们可以利用@XmlTransformation。它在概念上与 XmlAdapter 类似,但更容易在映射之间共享。

import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

import org.eclipse.persistence.oxm.annotations.XmlReadTransformer;
import org.eclipse.persistence.oxm.annotations.XmlTransformation;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformer;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;

@XmlAccessorType(XmlAccessType.FIELD)
public class ElemA {

    @XmlTransformation
    @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
    @XmlWriteTransformers({
        @XmlWriteTransformer(xpath="A_DATE/text()", transformerClass=DateFieldTransformer.class),
        @XmlWriteTransformer(xpath="A_TIME/text()", transformerClass=TimeFieldTransformer.class),
    })
    public Date aDate;

    @XmlElement(name="STRING")
    private String string;
}

ElemB

import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

import org.eclipse.persistence.oxm.annotations.XmlReadTransformer;
import org.eclipse.persistence.oxm.annotations.XmlTransformation;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformer;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;

@XmlAccessorType(XmlAccessType.FIELD)
public class ElemB {

    @XmlTransformation
    @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
    @XmlWriteTransformers({
        @XmlWriteTransformer(xpath="B_DATE/text()", transformerClass=DateFieldTransformer.class),
        @XmlWriteTransformer(xpath="B_TIME/text()", transformerClass=TimeFieldTransformer.class),
    })
    private Date bDate;

    @XmlElement(name="NUM")
    private int num;

    @XmlTransformation
    @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
    @XmlWriteTransformers({
        @XmlWriteTransformer(xpath="C_DATE/text()", transformerClass=DateFieldTransformer.class),
        @XmlWriteTransformer(xpath="C_TIME/text()", transformerClass=TimeFieldTransformer.class),
    })
    private Date cDate;

}

DateAttributeTransformer

属性转换器负责解组 Date 对象。

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
import org.eclipse.persistence.mappings.transformers.AttributeTransformer;
import org.eclipse.persistence.sessions.Record;
import org.eclipse.persistence.sessions.Session;

public class DateAttributeTransformer implements AttributeTransformer {

    private AbstractTransformationMapping mapping;
    private SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");

    public void initialize(AbstractTransformationMapping mapping) {
        this.mapping = mapping;
    }

    public Object buildAttributeValue(Record record, Object instance, Session session) {
        try {
            String dateString = null;
            String timeString = null;

            for(DatabaseField field : mapping.getFields()) {
                if(field.getName().contains("DATE")) {
                    dateString = (String) record.get(field);
                } else {
                    timeString = (String) record.get(field);
                }
            }
            return yyyyMMddHHmmss.parseObject(dateString + timeString);
        } catch(ParseException e) {
            throw new RuntimeException(e);
        }
    }

}

DateFieldTransformer

字段转换器负责编组 Date 对象。

import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
import org.eclipse.persistence.mappings.transformers.FieldTransformer;
import org.eclipse.persistence.sessions.Session;

public class DateFieldTransformer implements FieldTransformer {

    private AbstractTransformationMapping mapping;
    private SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");

    public void initialize(AbstractTransformationMapping mapping) {
        this.mapping = mapping;
    }

    public Object buildFieldValue(Object instance, String xPath, Session session) {
        Date date = (Date) mapping.getAttributeValueFromObject(instance);
        return yyyyMMdd.format(date);
    }

}

TimeFieldTransformer

import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
import org.eclipse.persistence.mappings.transformers.FieldTransformer;
import org.eclipse.persistence.sessions.Session;

public class TimeFieldTransformer implements FieldTransformer {

    private AbstractTransformationMapping mapping;
    private SimpleDateFormat HHmmss = new SimpleDateFormat("HHmmss");

    public void initialize(AbstractTransformationMapping mapping) {
        this.mapping = mapping;
    }

    public Object buildFieldValue(Object instance, String xPath, Session session) {
        Date date = (Date) mapping.getAttributeValueFromObject(instance);
        return HHmmss.format(date);
    }

}

示例程序

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum41/input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

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

}

XML文档

<ROOT> 
    <ELEM_A> 
        <A_DATE>20100825</A_DATE> 
        <A_TIME>141500</A_TIME>
        <!-- other elements, maybe also other or date/time combinations --> 
        <STRING>ABC</STRING> 
    </ELEM_A> 
    <ELEM_B> 
        <B_DATE>20100825</B_DATE> 
        <B_TIME>153000</B_TIME>
        <NUM>123</NUM> 
        <C_DATE>20100825</C_DATE> 
        <C_TIME>154500</C_TIME>
    </ELEM_B> 
</ROOT> 

上面所示的代码需要当前正在开发的EclipseLink 2.2。每晚构建可在此处获得:

当前发布的 EclipseLink 2.1 版本支持上述内容,但配置略有不同。如果您有兴趣探索此选项,我们可以讨论适当的设置。

Instead of using the JAXB RI (Metro), you could use the MOXy JAXB implementation (I'm the tech lead). It has some extensions that will make mapping this scenario fairly easy.

jaxb.properties

To use MOXy as your JAXB implementation you need to add a file named jaxb.properties in the same package as your model classes with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Root

import javax.xml.bind.annotation.*;

@XmlRootElement(name="ROOT")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement(name="ELEM_A")
    private ElemA elemA;

    @XmlElement(name="ELEM_B")
    private ElemB elemB;

}

ElemA

We can leverate @XmlTransformation. It is similar in concept to XmlAdapter, but easier to share among mappings.

import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

import org.eclipse.persistence.oxm.annotations.XmlReadTransformer;
import org.eclipse.persistence.oxm.annotations.XmlTransformation;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformer;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;

@XmlAccessorType(XmlAccessType.FIELD)
public class ElemA {

    @XmlTransformation
    @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
    @XmlWriteTransformers({
        @XmlWriteTransformer(xpath="A_DATE/text()", transformerClass=DateFieldTransformer.class),
        @XmlWriteTransformer(xpath="A_TIME/text()", transformerClass=TimeFieldTransformer.class),
    })
    public Date aDate;

    @XmlElement(name="STRING")
    private String string;
}

ElemB

import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

import org.eclipse.persistence.oxm.annotations.XmlReadTransformer;
import org.eclipse.persistence.oxm.annotations.XmlTransformation;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformer;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;

@XmlAccessorType(XmlAccessType.FIELD)
public class ElemB {

    @XmlTransformation
    @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
    @XmlWriteTransformers({
        @XmlWriteTransformer(xpath="B_DATE/text()", transformerClass=DateFieldTransformer.class),
        @XmlWriteTransformer(xpath="B_TIME/text()", transformerClass=TimeFieldTransformer.class),
    })
    private Date bDate;

    @XmlElement(name="NUM")
    private int num;

    @XmlTransformation
    @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
    @XmlWriteTransformers({
        @XmlWriteTransformer(xpath="C_DATE/text()", transformerClass=DateFieldTransformer.class),
        @XmlWriteTransformer(xpath="C_TIME/text()", transformerClass=TimeFieldTransformer.class),
    })
    private Date cDate;

}

DateAttributeTransformer

The attribute transformer is responsible for unmarshalling the Date object.

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
import org.eclipse.persistence.mappings.transformers.AttributeTransformer;
import org.eclipse.persistence.sessions.Record;
import org.eclipse.persistence.sessions.Session;

public class DateAttributeTransformer implements AttributeTransformer {

    private AbstractTransformationMapping mapping;
    private SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");

    public void initialize(AbstractTransformationMapping mapping) {
        this.mapping = mapping;
    }

    public Object buildAttributeValue(Record record, Object instance, Session session) {
        try {
            String dateString = null;
            String timeString = null;

            for(DatabaseField field : mapping.getFields()) {
                if(field.getName().contains("DATE")) {
                    dateString = (String) record.get(field);
                } else {
                    timeString = (String) record.get(field);
                }
            }
            return yyyyMMddHHmmss.parseObject(dateString + timeString);
        } catch(ParseException e) {
            throw new RuntimeException(e);
        }
    }

}

DateFieldTransformer

The field transformers are responsible for marshalling the Date object.

import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
import org.eclipse.persistence.mappings.transformers.FieldTransformer;
import org.eclipse.persistence.sessions.Session;

public class DateFieldTransformer implements FieldTransformer {

    private AbstractTransformationMapping mapping;
    private SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");

    public void initialize(AbstractTransformationMapping mapping) {
        this.mapping = mapping;
    }

    public Object buildFieldValue(Object instance, String xPath, Session session) {
        Date date = (Date) mapping.getAttributeValueFromObject(instance);
        return yyyyMMdd.format(date);
    }

}

TimeFieldTransformer

import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
import org.eclipse.persistence.mappings.transformers.FieldTransformer;
import org.eclipse.persistence.sessions.Session;

public class TimeFieldTransformer implements FieldTransformer {

    private AbstractTransformationMapping mapping;
    private SimpleDateFormat HHmmss = new SimpleDateFormat("HHmmss");

    public void initialize(AbstractTransformationMapping mapping) {
        this.mapping = mapping;
    }

    public Object buildFieldValue(Object instance, String xPath, Session session) {
        Date date = (Date) mapping.getAttributeValueFromObject(instance);
        return HHmmss.format(date);
    }

}

Sample Program

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum41/input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

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

}

XML Document

<ROOT> 
    <ELEM_A> 
        <A_DATE>20100825</A_DATE> 
        <A_TIME>141500</A_TIME>
        <!-- other elements, maybe also other or date/time combinations --> 
        <STRING>ABC</STRING> 
    </ELEM_A> 
    <ELEM_B> 
        <B_DATE>20100825</B_DATE> 
        <B_TIME>153000</B_TIME>
        <NUM>123</NUM> 
        <C_DATE>20100825</C_DATE> 
        <C_TIME>154500</C_TIME>
    </ELEM_B> 
</ROOT> 

The code as shown above requires EclipseLink 2.2 currently under development. A nightly builds are available here:

The current released version of EclipseLink 2.1 supports the above, but with a slightly different configuration. We can discuss the appropriate setup if you are interested in exploring this option.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文