سؤال

I'm trying to implement a specific behavior with Hibernate (3.6), on wich I'm not able to find any information.

Basically, I'd like to have a many-to-many relationship between 2 tables, as show below :

class Task {
    private Long id;
    private Set<Person> personsInCharge;
    private Set<Person> contributors;
    private Set<Person> validators;
}

class Person {
    private Long id;
    private Set<Task> tasks;
}

My issue is that a same person can have different roles depending on the task, or different roles for the same task, therefore it's not possible to define a "fixed" role for the person. So, it would be convenient if I could have a join table on which I could add a specific "role" as a third primary key, and then use custom loaders in my mapping files. Is there a way to define this using Hibernate, or should I create a specific transitional POJO (or "handmade" table) ?

Thanks in advance for any feedback.

هل كانت مفيدة؟

المحلول

This sounds more like a standard 'Many to Many' mapping to me and it can be achieved as follows in my opinion..

    class Task {

    private Long id;


    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "task_incharge", joinColumns = { @JoinColumn(name = "task_id",  referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "person_id", referencedColumnName = "id") })    
    private Set<Person> personsInCharge;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "task_contributors", joinColumns = { @JoinColumn(name = "task_id",  referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "person_id", referencedColumnName = "id") })    
    private Set<Person> contributors;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "task_validators", joinColumns = { @JoinColumn(name = "task_id",  referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "person_id", referencedColumnName = "id") })  
    private Set<Person> validators;

}

Here we have three additional intermediate tables i.e. task_incharge, task_contributors and task_validators.

Similarly you need many-to-many collections in the Person class i.e.

private Set<Task> contributedTasks;
private Set<Task> validatedTasks;
private Set<Task> inchargeOf;

use same mapping tables for these as well just reverse the order of @JoinColumn inside @JoinTable to order inside

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top