Home > database >  Multiple entities connected
Multiple entities connected

Time:10-26

i want to ask you for an example of how should i do the next thing: I have 2 model classes, let's call them class A and B, each class A object has one class B object.

I built a react client, and a springboot java api to save new class A objects in a mysql db.

Now i have to take care of the class B objects, the ideal case is to save the class A object in the db, get the id, and then create a class B object in another table, with the same id as its coresponding class A object.

What i can do easily is: on the frontend, call the api to save the class A object, wait for the response to get its id, and make another call to another api to save the class B object, but i think this is risky, because something could happen between calls and the class B object could end up not being saved.

Can you suggest me how to fix this problem?

CodePudding user response:

You should go through the mapping concept of hibernate, if you are using hibernate use @OneToOne mapping. and you can easily solve this, it will become pretty easy to handle the data once you apply the mapping because hibernate handles the things, you can also configure the operations for the mapped model class by defining its cascade type, you can refer to this video One to one mapping to understand mapping especially one-to-one mapping.

class A{
  @OneToOne(cascade = CascadeType.All, fetch = FetchType.Eager)
  @JoinColumn(name = "b_id")
  private B b;
}

it's a unidirectional relationship you can also make it bi-directional, according to your application need.

CodePudding user response:

This can be done with the help of a one-to-one relationship of one class with another class.

Use @OnetoOne Annotation. You can also you can refer to this for more information on hibernate mappings.

Also, check this one https://www.javatpoint.com/hibernate-one-to-one-example-using-annotation.

  • Related