简体   繁体   中英

Properly Implementing a One to Many Unidirectional Relationship in Hibernate

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM