T
T
TostMaria2014-12-09 15:39:25
Java
TostMaria, 2014-12-09 15:39:25

Hibernate many to many with additional attributes?

Good afternoon!
Question about many-to-many relationship through hibernate xml-configuration (Java). I found many simple examples, but they do not suit me. In all of these examples, the table that provides the user_achievement relationship has only two columns - user id and achievement id, but I need to store additional data there, such as the date the user acquired the achievement and others. In addition, in all examples, the many-to-many relationship is described through Set, but I need it through List, because the order in which the user acquired achievements is important.
Those. essence of the question:
There are two classes user - User, and achievement - Achievement, between them it is required to describe the many-to-many ratio through xml hibernate, so that you can add the date of acquisition of the achievement and other parameters.
How to do this, and is it possible in principle?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Smirnov, 2014-12-10
@TostMaria

I think you really need one-to-many, i.e. the User entity holds a list of Achievement entities. At the same time, the Achievement entity has fields that describe the specific achievement of a particular user (date of receipt and other parameters), as well as a link to the type of achievement (the next one-to-many level). Regarding Set/List - as you declare in the class, it will be so, but for sorting, you need to specify order-by in .hbm.xml.
More or less like this:

public class User {
    private List<Achievement> achievements;
    get...
    set...
}

public class Achievement {
    private User user;
    private Date createDate;
    private DicAchievementType type;//справочник типов достижений
    get...
    set...
}

User.hbm.xml
<bag name="achievements" inverse="true" cascade="all,delete-orphan" order-by="CREATE_DATE">
    <key column="user_id"/>
    <one-to-many class="Achievement"/>
</bag>

Achievement.hbm.xml
<many-to-one name="user" column="user_id" class="User"/>
<many-to-one name="type" column="achievement_type_id" class="DicAchievementType"/>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question