简体   繁体   中英

One-To-Many with the same entity

I'm doing reverse engineering from the database schema (using Hibernate) and I want to have following in the resulting entity:

public class Task implements Serializable {
    ...
    List<Task> dependentTasks = new ArrayList<Task>(0);
    ...
}

If I do it as a 1:N relationship, it will generate this:

public class Task implements Serializable {
    ... 
    Task task; 
    List<Task> dependentTasks = new ArrayList<Task>(0);
    ...
}

If I do it as a M:N relationship, it will generate two same Lists:

public class Task implements Serializable {
    ...
    List<Task> dependentTasks_1 = new ArrayList<Task>(0);
    List<Task> dependentTasks_2 = new ArrayList<Task>(0);
    ...
}

EDIT -- your reverse engineering tool is creating Task task; to make the relationship bidirectional. You can remove the property from the object and the resulting configuration files, but the relationship will be unidirectional -- you will no longer be able to go from children to parents.

I bet the underlying table has a column for a task's parent called something like task_id. If you remove the reference to the parent, that column will no longer be used by your domain model.

This is the danger of using tools to do the work for you. You should dig into the documentation and understand the difference between unidirectional and bidirectional relationships in hibernate. Just curious, why does your domain class have to not have the 'task' property?

EDIT -- in reference to you comment about changing the constraint on the table, be careful. The legacy data model you have IMPLIES that tasks should have references to their parents. So in changing this, you are changing the semantics of the relationships your legacy model contains. You might break things.

I think it is a better id to leave the DB where it is, and make the model you are building conform to the semantics of the underlying relationship. In other words, to say 'we don't want the task' property doesn't make sense -- your table structure implies that you want that, and it might have been designed that way for a reason.

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