0

I have four classes (A, B, C, D) all connected by relationship. I am using hibernate to store them in mysql database.

Structure of classes

Class A {
    Integer id;           //primary key
    List<B> listOfB;      //one to many with B class, able to store order of B's

    //some other fields
}

/* This class can contain list of c, or list of d, or both.
 * need to keep order among c and d also if contains both list
 * for eg, B has list of c(c1, c2, c3) and D (d1, d2, d3)
 * order can be c1, d1, c2, d3, c3, d2
 */
Class B {
    Integer id;           //primary key
    List<C> listOfC;      //one to many with D class, able to store order of C's
    List<D> listOfD;      //one to many with C class, able to store order of D's

    //How to store order between list of c and list of d?       

     //some other field
}

Class C {
    Integer id;           //primary key
    List<D> listOfD;      //one to many with D class, able to store order of D's

     //some other field
}

Class D {
    Integer id;           //primary key
    String value;         //some value

}

Here relation between A and B is one to many, B to C is one to many, B to D is one to many, C to D is one to many.

List has been used just to keep track of order between objects. But I want also to keep track of order of list of c and d in B class.

B can have following steps:
 1. C1
 2. D1
 3. c2
 4. D2

With the current design I am not able to store the order between c and d.

please suggest some design. Thank you

1 Answer 1

2

You could inherit C and D from an abstract entity and use a single list in B.

The abstract entity:

@Entity
@Inheritance
@DiscriminatorColumn(name = "discr")
public abstract class X {
    Integer id; 
    // ...
}

Then extend it:

@Entity
@DiscriminatorValue("c")
public class C extends X {
    List<D> listOfD;
    // ...
}

@Entity
@DiscriminatorValue("d")
public class D extends X {
    String value;     
    // ...
}

and finally:

@Entity
public class B {
    Integer id;
    List<X> listOfX; // single list for C and D
}

Take a look at inheritance stategies. In my example I'm using single table strategy.

Also take a look to this

Obviously you need to add relationship annotations.

Sign up to request clarification or add additional context in comments.

2 Comments

but how hibernate will store them in db? The structure of C and D can be different
@Raj take a look at Hibernate documentation (link in the answer). You can have several tables (one for each type) or just a single table one with all the fields, plus a discriminator column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.