List is a collection in which the indexes of the elements are maintained. Hibernate maintains the same by adding an index column to the collection table. Let’s see how it’s done using the XML mapping. First we need to add the Persistent class. We’ll borrow the Student class from the previous posts and will configure a list collection property in it.

public class Student {

    Long id;
    String firstName;
    String lastName;
    List<String> classes = new ArrayList<String>();

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public List<String> getClasses() {
        return classes;
    }

    public void setClasses(List<String> classes) {
        this.classes = classes;
    }
}

Now, let’s add the mapping XML file.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.jft.prashant.Student" table="STUDENTS">

    <id name="id" column="STUDENT_ID" type="long">
        <generator class="increment"/>
    </id>

    <property name="firstName" column="STUDENT_FIRST_NAME" type="string" />

    <property name="lastName" column="STUDENT_LAST_NAME" type="string" />

    <list name="classes" table="STUDENT_CLASSES">

        <key column="STUDENT_ID"/>

        <list-index column="POSITION" />

        <element type="string" column="STUDENT_CLASSES_NAME" not-null="true" />
    </list>
</class>
</hibernate-mapping>

STUDENT_ID column in STUDENT_CLASSES collection table references to the primary key of STUDENTS table. POSITION column is populated automatically with the indexes by Hibernate. Hibernate also adds the primary key on STUDENT_CLASSES collection table which is composite of STUDENT_ID and POSITION for allowing the duplicate elements in the collection. That’s all to configuring List collection in the persistent Hibernate class using XML mapping.