hibernatexsdjaxbhyperjaxb

Hyperjaxb3: Create lookup table from enumeration element


I have an xsd file which includes an element with an enumeration constraint:

<xs:complexType name="Request">
    <xs:sequence>
        <xs:element name="CommsAddress" type="xs:string" />
        <xs:element name="CommsAddressType">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value="EMAIL"/>
                    <xs:enumeration value="PHONE"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:element>
        ...

I would like the CommsAddressType field in the generated Java class to be a generated enum with the values EMAIL and PHONE. In turn, I would like Hibernate to automatically generate my database schema with a CommsAddressType table containing two rows with the values EMAIL and PHONE. The Request table can then simply reference these with a CommsAddressTypeId column.

Currently, Hyperjaxb3 generates my Request class with a CommsAddressType field of type String:

@XmlElement(name="CommsAddressType")
protected String commsAddressType

and the schema is generated so that the Request table has a CommsAddressType column of type VARCHAR. This will obviously result in a lot of unnecessary duplicated data.

Is there any way of achieving what I described above? Also, as I am exposing the xsd to my customer, I would like to avoid including any jaxb or hyperjaxb tags in the schema if possible.


Solution

  • Disclaimer: I'm the author of Hyperjaxb.

    If you make your enumerated types to become enums in Java, Hyperjaxb will handle them as enums, not as strings. For this you can, for instance, customize your simple type with:

    <jaxb:typesafeEnumClass/>
    

    See this example.

    Hyperjaxb will map corrsponding properties as @Enumerated.

    No, you can't generate a lookup table but you can customize how the enum is mapped in the database. For instance, you can make it mapped as EnumType.ORDINAL:

    <hj:basic><orm:enumerated>ORDINAL</orm:enumerated></hj:basic>
    

    Example.

    Actually, with enums you don't really need lookup tables for JPA. JPA will map enums correctly according to the speified EnumType mapping.

    But you may need a lookup table for your own purposes - like being able to produce human-readable values in joined queries.

    In this case I'd recommend mapping the enum as ORDINAL and adding a lookup table plus corresponding foreign keys on your own DDL scripts.

    And yes, you can do all of the described customizations in a separate bindings file (normally bindings.xjb), you don't have to do it directly in the schema. See test projects here, there is plenty of examples. Just look for *.xjb files in src/main/resources directories.