use the one-to-many or many-to-one
Two class:
Department Task
One department can have many tasks. One task can only belong to one department.
So use one-to-many or many-to-one?
one-to-many
class Department{
private Set tasks;
}
class Task{
......
}
//
Department.hbm.xml
....
<set name="tasks">
<key column="departId" />
<one-to-many class="Task" />
&开发者_运维技巧lt;/set>
.....
many-to-one
class Department{
}
class Task{
Department depart;
}
//
Task.hbm.xml
....
<property name="depart">
<many-to-one class="Department" />
</property>
.....
What's the difference?
BTW,what is the difference between use the set and list?
And example using list(xml configuration)?
A Task cannot exist without a Department I suppose, but a Department can exist without a Task associated with it. So the dependency is on the Task to attach itself to the Department, hence should be the owning side in the relationship. Many-to-One should be your choice here.
Your choices would depend on 2 things:
What are various scenarios under which this relationships are used. For e.g. if you need to list your tasks by departments than One to Many is what you would need. It would also be easy for you to load them once since you are using Hibernate.
If you update your tasks by department then you need the other relationship too.
However, remember this decisions have deep roots into your domain model and how you want to structure it. What are the usecases under which these entities are used. I would strongly recommend reading this SO thread and moreover watch this video by Eric Evans.
Hope that helps.
Just by looking at the structure, I would choose many-to-one.
If a task has to be reassigned to another department, then only the task object needs to be altered, not the original department object.
From java collections, a Set does not allow duplicates, whereas a List might
You should define a join table called DEPARTMENT_TASKS and have a ManyToMany relationship between them.
精彩评论