简体   繁体   中英

Parent child relationship hibernate

I've been trying to recreate the parent/child scenario with hibernate, I used this as an example (very new to hibernate):

http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/

My situation is similar to this. I am working on a project that has some task objects which should be part of some task flow object.

  • So there are two entities task and taskflow.

  • Taskflow should have many or at least one task.

  • There are already some tasks in the task table, now I want to insert some entries into taskflow table so that taskflow object has list or set of tasks.

Forgot to mention in my original question :

  • Task can be inside many different task flows

My taskflow looks something like :

class Taskflow{
   int taskflowid;
   String taskflowname;
   List<Task> tasklist;
}

in the database taskflow has 2 fields taskflowid and taskflowname .

This is how Task looks like :

class Task{
 //many properties/fields
}

Taking this example into consideration when compared to examples I googled, there is always some kind of relation from Task back to the TaskFlow. Is that necessary? I just want taskflow to have reference to task. Am I thinking this one all wrong?

If you don't declare relationship it would be simple member variables. In order to hibernate understand that you have one to many relationship you need to specify it in some for .hbm , annotation

@OneToMany //This for hibernate to understand that you have one to many relationship with Task
List<Task> tasklist;

inside Task

@ManyToOne
Taskflow taskFlow

Remember default names will be used to generate column names. Please refer tutorial over here

Hibernate supports relationships of different cardinality (one-to-one, one-to-many/many-to-one, many-to-many) and different directionality (unidirectional or bidirectional).

In your case you have a many-to-many relationship, which can be either unidirectional (if Task don't need to contain a collection of all TaskFlow s it's a part of), or bidirectional.

For example, a unidirectional relatioship from TaskFlow to Task :

class Taskflow {
    ...
    @ManyToMany
    private List<Task> tasks;
    ...
}

See also:

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