jaxbjaxb2jaxb2-basics

JAXB: using @XmlID along with Hibernate @Id


I have following hibernate property:

@Id()   
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id = null;

I want to add JAXB annotation @XmlID to this id but @XmlID can only be applied to String data types. How can I solve this problem.


Solution

  • Use @XmlJavaTypeAdapter(IDAdapter.class) along with @XmlID where IDAdapter is

    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);
        }
    
    }