开发者

Map ArrayList with Hibernate

I just coded my first Hibernate examples.

The database connection works and I understand how I can map a String from a POJO to a database field:

private String firstName;

And in the mapping file:

<property name="firstName" type="java.lang.String">
    <column name="FIRSTNAME" />
</property>

But how can I map an ArrayList to the database? A simpl example from the mapping xml file would be appreciated.

Cheers

UPDATE

I switched to List instead of ArrayList found an example. Now I map as follows:

    <list name开发者_JS百科="test" inverse="false" table="CONTACT" lazy="true">
        <key>
            <column name="ID" />
        </key>
        <list-index></list-index>
        <element type="java.lang.String">
            <column name="TEST" />
        </element>
    </list>

Unfortunately, I get an exception that I do not understand:

Exception in thread "main" org.hibernate.MappingException: Foreign key (FK6382B0003257FF7F:CONTACT [ID])) must have same number of columns as the referenced primary key (CONTACT [ID,idx])

Any ideas?

Cheers


I notice that you are using XML to map your POJOs. You will find some information about that here.

for example:

   <list name="myArrayListProperty" cascade="all">
        <key column="parent_id"/>
        <index column="idx"/>
        <one-to-many class="WhatIsInTheList"/>
    </list>

However, using annotations have some advantages. This link will explain how to map any collection using annotations.


See the collection mapping section of the docs. There are multiple ways to map a list (one-to-many, many-to-many, a collection of elements). You can map it as a list or as a bag, so read the whole section.


You have a little error in the XML configuration:

When you have a list the solution to map this list using a database is to link with a additional table, so instead of doing:

<list name="test" inverse="false" table="CONTACT" lazy="true">
        <key>
            <column name="ID" />
        </key>
        <list-index></list-index>
        <element type="java.lang.String">
            <column name="TEST" />
        </element>
</list>

You should have to do map to a new data table that holds the list values:

<list name="test" inverse="false" table="CONTACT_test" lazy="true">
        <key>
            <column name="ID" />
        </key>
        <list-index></list-index>
        <element type="java.lang.String">
            <column name="TEST" />
        </element>
</list>

Hibernate automatically creates the new table for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜