Set One to many in hibernate

A One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element. We already have seen how to map Set collection in hibernate, so if you already learned Set mapping then you are all set to go with one-to-many mapping.

It is non-index based and will not allow duplicate elements.

Let's see the persistent class that has set objects. In this case, there can be many answers for a question and each answer may have its own informations that is why we have used set element to represent a collection of answers.


package com.javatportal;

import java.util.List;

public class Question {
private int id;
private String qname;
private Set<Answer> answers;
//getters and setters

}

The Answer class has its own informations such as id, answername, postedBy etc.

 
package com.javatportal;

public class Answer {
private int id;
private String answername;
private String postedBy;
//getters and setters

}
}

The Question class has set object that have entity reference (i.e. Answer class object). In such case, we need to use one-to-many of set to map this object. Let's see how we can map it.

 
<set name="answers" cascade="all">
          <key column="qid"></key>
          <one-to-many class="com.javatpoint.Answer"/>
</set>