It’s a common requirement to configure value-type collections in the entity. In this post I’ll walk you through the steps for configuring the Set of value-type collection. We know Set doesn’t allow duplicate entries so it will be interesting to see how this is managed by the Hibernate. Let’s first add a persistent class which will contain a collection property.

public class Student {

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

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

and now we add the mapping file for the Student class:

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

<set name="classes" table="STUDENT_CLASSES_SET">
<key column="STUDENT_ID"/>
<element column="STUDENT_CLASS" not-null="true" type="string" />
</set>

</class>
</hibernate-mapping>

element is used to map the Set collection in hibernate. Hibernate creates a collection table where all the elements are persisted. STUDENT_ID will be the foreign key that points to the primary key STUDENT_ID of the STUDENTS table. Hibernate also adds the primary key on STUDENT_CLASSES_SET which is composite of its STUDENT_ID and STUDENT_CLASS columns for avoiding the duplicate entries. That’s all the important gotchas to configuration of value-type Set in a persistent class in Hibernate.