Search code examples
hibernatehibernate-mapping

<element> vs <composite-element> in Hibernate


What is the difference between <element> and <composite-element>? I have seen both <composite-element> and <element> tags used within tag. Are these elements used for collections? In what situations do each of these elements apply?


Solution

  • <element> is used when you want to map a collection of "simple" values. See this example from 6.2.4. Collections of values and many-to-many associations

    <set name="names" table="person_names">
        <key column="person_id"/>
        <element column="person_name" type="string"/>
    </set>
    

    <composite-element> is for when you want to map a collection of components, i.e. dumb classes that are themselves made up of simple types. This example from 8.2. Collections of dependent objects:

    <set name="someNames" table="some_names" lazy="true">
        <key column="id"/>
        <composite-element class="eg.Name"> <!-- class attribute required -->
            <property name="initial"/>
            <property name="first"/>
            <property name="last"/>
        </composite-element>
    </set>