Bag is an unordered collection that permits duplicate elements. Let’s edit the Student class from our previous post in which a Set property was configured. We’ll use the same class but we’ll replace the set with Bag. Java doesn’t have the implementation of bag however java.util.Collection interface has bag semantics. We’ll use for configuring the bag and in the Student class we’ll initialize the Collection property with ArrayList. Here’s the Student class

public class Student {

    Long id;
    String firstName;
    String lastName;
    Collection<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 Collection<String> getClasses() {
        return classes;
    }

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

Let’s see the mapping XML now:

<?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" />

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

        <collection-id column="STUDENT_CLASS_ID" type="long">
            <generator class="sequence"/>
        </collection-id>

        <key column="CLASS_ID"/>

        <element type="string" column="STUDENT_CLASS_NAME" not-null="true"/>
    </idbag>

</class>
</hibernate-mapping>

Hibernate adds the primary key column STUDENT_CLASS_ID to STUDENT_CLASSES. As usual CLASS_ID references to the records in STUDENTS table and STUDENT_CLASS_NAME contains the name. Here’s an important point. We can’t use native id generation strategy in the collection-id. You are required to provide a concrete strategy for id generation. that’s all to configuring bags in Hibernate.