How to create composite unique key in Hybris

Viewed 2942

Is it possible to create composite unique key in Hybris through items.xml?

In the given example:

        <itemtype  code="SimpleDevice">
            <deployment table="simpleDevice" typecode="20063"/>
            <attributes>
                <attribute qualifier="productId" type="java.lang.String">
                    <persistence type="property" />
                    <modifiers unique="true" optional="false" initial="true"/>
                    <description>Device's product ID</description>
                </attribute>
                <attribute qualifier="serialNumber" type="java.lang.String">
                    <persistence type="property" />
                    <modifiers unique="true" optional="false" initial="true"/>
                    <description>Device's serial number</description>
                </attribute>
            </attributes>
        </itemtype>

How do I combine the 2 attribute to make them behave as a composite unique key? My plan B it's to use some interceptor to check if such a combination already exists before creating it. But I want to avoid overloading the DB when importing several items by Impex.

2 Answers

You need to add new unique index in indexes element for using multiple attributes together in an index.

<itemtype  code="SimpleDevice">
    <deployment table="simpleDevice" typecode="20063"/>
    <attributes>
        <attribute qualifier="productId" type="java.lang.String">
            <persistence type="property" />
            <modifiers unique="true" optional="false" initial="true"/>
            <description>Device's product ID</description>
        </attribute>
        <attribute qualifier="serialNumber" type="java.lang.String">
            <persistence type="property" />
            <modifiers unique="true" optional="false" initial="true"/>
            <description>Device's serial number</description>
        </attribute>
    </attributes>
    <indexes>
        <index name="SimpleDeviceIdx" unique="true">
            <key attribute="productId" />
            <key attribute="serialNumber" />
        </index>
    </indexes>  
</itemtype>

The given example is already correct. It makes the combination of productId and serialNumber unique.

Related