zono
zono

Reputation: 8584

How to set up "one-to-many" mapping of List objects by XML without index column

I can set up "one-to-many" mapping of List objects by using annotations, however using XML is not. Could you tell me how to set up using XML mapping. Any help will be appreciated.

Question. Do I need "INDEX" column when I associate some List objects using XML mapping?

annotation mapping -> It works as expected:

@Entity
@Table(name = "ITEM")
public class Item {

    @Id
    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @OneToMany(targetEntity = ItemDetail.class)
    @JoinColumn(name = "ITEM_ID")
    private List<ItemDetail> itemDetails;

@Entity
@Table(name = "ITEM_DETAIL")
public class ItemDetail {

    @Id
    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "ITEM_ID")
    private Long itemId;

XML mapping -> It does not work as expected. "Error parsing XML" error is occurred. It seems to need "INDEX column" information:

<hibernate-mapping>
    <class name="jp.sample.entity.Item" table="ITEM">
        <id name="id" type="java.lang.Long">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" />
        </property>

        <list name="itemDetails" cascade="all">
            <key column="ITEM_ID" />
            <one-to-many class="jp.sample.entity.ItemDetail" />
        </list>

    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="jp.sample.entity.ItemDetail" table="ITEM_DETAIL">
        <id name="id" type="java.lang.Long">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" />
        </property>
        <property name="itemId" type="java.lang.Long">
            <column name="ITEM_ID" />
        </property>
    </class>
</hibernate-mapping>

Upvotes: 5

Views: 14853

Answers (1)

matt b
matt b

Reputation: 139931

A <list> in a Hibernate Mapping XML file requires a <list-index>, since you are telling Hibernate that you want to map an ordered collection.

If you do not care about the position of elements in the collection, you should be using a <bag>, or if you change the collection type in the Java class to Set, a <set>:

If your table does not have an index column, and you still wish to use List as the property type, you can map the property as a Hibernate <bag>. A bag does not retain its order when it is retrieved from the database, but it can be optionally sorted or ordered.

Upvotes: 8

Related Questions