一尘不染

通过其ID序列化JAXB对象?

hibernate

在我的数据模型中,我可以达到以下目的:

@Entity
public class Target {

    @Id 
    @GeneratedValue
    private Long id;

    /* ...etc... */
}

@Entity
public class Dependency {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne(optional=false)
    @Column(name="target_id")
    private Target target;

    /* ...etc... */
}

我已经可以序列化Target了,但是我需要序列化Dependency。本质上,我需要的是这样的:

<dependency>
    <id>100</id>
    <targetId>200</targetId>
</dependency>

有没有办法在JAXB批注中执行此操作而不修改我的模型?


阅读 219

收藏
2020-06-20

共1个答案

一尘不染

您可以XmlAdapter在此用例中使用:

package forum7278406;

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

public class TargetAdapter extends XmlAdapter<Long, Target> {

    @Override
    public Long marshal(Target target) throws Exception {
        return target.getId();
    }

    @Override
    public Target unmarshal(Long id) throws Exception {
        Target target = new Target();
        target.setId(id);
        return target;
    }

}

XmlAdapter登记在Dependency使用类@XmlJavaTypeAdapter注释:

package forum7278406;

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

@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Dependency {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne(optional=false)
    @Column(name="target_id")
    @XmlJavaTypeAdapter(TargetAdapter.class)
    private Target target;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Target getTarget() {
        return target;
    }

    public void setTarget(Target target) {
        this.target = target;
    }

}

走得更远

除了创建新的实例外,Target我们还可以使用EntityManager从数据库查询相应的实例。我们XmlAdapter将更改为如下所示:

package forum7278406;

import javax.persistence.EntityManager;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class TargetAdapter extends XmlAdapter<Long, Target> {

    EntityManager entityManager;

    public TargetAdapter() {
    }

    public TargetAdapter(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public Long marshal(Target target) throws Exception {
        return target.getId();
    }

    @Override
    public Target unmarshal(Long id) throws Exception {
        Target target = null;
        if(null != entityManager) {
            target = entityManager.find(Target.class, id);
        }
        if(null == target) {
            target = new Target();
            target.setId(id);
        }
        return target;
    }

}

现在设置的情况下EntityManager我们的XmlAdapter,我们可以做到以下几点:

Unmarshaller umarshaller = jaxbContext.createUnmarshaller();
TargetAdapter targetAdatper = new TargetAdapter(entityManager);
unmarshaller.setAdapter(targetAdapter);
2020-06-20