API REST WITH Spring Boot JPA AND HIBERNATE

1

I have a project where we are doing a restfull service with:

  • Spring boot
  • JPA
  • JDBC
  • WEB SPRING (MVC)
  • Hibernate

Well currently I do not have much experience with hibernate in the onetomany relationship.

The detail is that for example, I have a parent class Recetas , in the recipes I have a list of ingredients where I have an object of type Recetas .

The onetomany of the recipe class maps it to the class of ingredients towards the recipe object, the detail is that I have an infinite loop.

Something like this:

RECETAS{
nombre:""
tiempo:""
etc.:""
ingredientes : [{nombre: "taltal","recetas":"{otro objeto de recetas}"}

]
}

And so the infinite cycle is followed inwards since each recipe object has an ingredient object and within the ingredients has a recipe object .. and so on. Any idea suggestion or recommendation? I have read all the sides that this is handled but I do not understand the concept very well.

    
asked by Monster 01.06.2018 в 08:20
source

1 answer

0

Afternoon but I hope it serves you.

It is called bidirectionality and is a somewhat new property for those who have not worked with hibernate and spring.

I pass the translated answer to here:

The difference with bidirectional relationships is that they provide access (navigation) in both directions, so that you can access from one point or another without the need to specify new queries.

It should be noted that navigation access is not always good, especially in "one-to-many" and "many-to-many" relationships. Imagine a Grupo containing thousands of Usuario ;

  • How would you access them? With that amount of Usuario you will usually need to apply a filter or a pager, so you need to execute a query in any way (Unless you use a collection filtering , which is like a hack for me.). In some cases developers tend to apply filtering in memory, which obviously is not good for performance. Keep in mind that this type of relationship can encourage these developers to use these types of relationships without considering the performance of them.
  • How would you add a new Usuario to Grupo ? Fortunately, Hibernate checks on the other side of the relationship when it persists, so you only need to make a set at Usuario.grupo . However, if you want to keep objects in memory consistently, you also need to add Usuario to Grupo.usuarios . That will make Hibernate look for all the elements Group.user of the database!

So I can not agree with the recommendations of best practices . You need to design the bidirectional relationship with great care, considering use cases (Do you need to access navigation in both directions?) And the possible implications on performance.

See also:

answered by 09.06.2018 в 16:01