views:

292

answers:

1

I'm trying to learn how to use Hibernate to implement Java Object Persistence. Specifically, I'm trying to figure out how to implement a unidirectional one to many mapping. I've read the hibernate documentation and the numerous Stackoverflow questions on the subject and they are not entirely clear, so I'd like to know what the correct way to implement this is.

Here is an (extremely simplified) example of the sort of Java objects I'm trying to map:

public class Student {
    private List<StudentGrade> grades;

}

public class StudentGrade {
    private char letterGrade;
    private double percentageGrade;
}

So the question is, how do I write the hbm.xml files to map this?

The hibernate documentation suggests that this, placed in the mapping file for Student, should be enough in this case. Assuming of course I have fully fleshed out mapping files for both Student and StudentGrade.

<many-to-one name="StudentGrade" column="grade_id" />

However, it only shows the mapping file and not the Java object accompanying it. In the mapping file, that many-to-one element is listed along with other properties. It isn't contained in a list or set element. Elsewhere where it does show a Java object that uses a Collection (a Set implemented as a HashTable in the example) it has a mapping file that looks like this:

<set name="events" table="PERSON_EVENT">
    <key column="PERSON_ID"/>
    <many-to-many column="EVENT_ID" class="Event"/>
</set>

That is also what I've seen in many StackOverflow questions. So what's the correct way to implement this?

+1  A: 

The two examples you've quoted are many-to-one and many-to-many mappings, neither of which is applicable to your model. You need a one-to-many mapping.

Given your Student and StudentGrade classes, you want something like this in your mapping descriptor for Student:

<list name="grades">
   <list-index column="idx"/>
</list>

You'll also need the class mapping for StudentGrade.

Are sure sure it's a list you want? Lists need an explicit list position column in the database, and I'm guessing you don't really need that. A Set or Bag is easier to map in Hibernate, and requires fewer database columns. See the docs for instructions on how to map bags, sets, maps, lists, etc.

skaffman
Yeah, I don't really need the explicit list index column. A suppose a set would be better. I have read that documentation several times. It isn't really clear because it often just shows the mapping file - with out showing the corresponding java objects. It's hard to figure out what mapping file should go to what java pattern. So, what would properly mapped set look like here? <set name="grades"><key column="studentID"><one-to-many class="StudentGrades"></set>? Is there anything that needs to go into the StudentGrades mapping file (aside from its properties)?
Daniel Bingham
That's pretty much it, yes. The `StudentGrades` mapping needs know nothing about it, just the properties, as you said.
skaffman