Skip to content
Advertisement

How to access a child element in a query using jpa and hibernate – SpringBoot

I would like to know how to query some child objects using their name as a parameter in Spring boot.

Let’s say I have a class parent with a one-to-many relationship with the child.

The child has a parameter called name. So I would like to query using like "%name%" so the query would return me a list with all the child that the query finds.

I would like to do something like this:

JavaScript

But using the children that one parent have, I would search it using the id of the parent. I don’t know if I am explaining it well, the thing is that I haven’t been able to achieve the join between the classes.

Thanks!

Edit. these are the classes that I have:

Compania

JavaScript

And my child class, default_group

JavaScript

So I would like to get the defaultGroups assigned to the Compania with id 1 where the name of the defaultGroup is like %x%. And I don’t know how to achieve this. Thanks!

Advertisement

Answer

If you have a Child entity in a parent entity Parent like this:

JavaScript

Then you can use a query like this:

JavaScript

And spring data will generate the query for you.


If we want to get childs of a parent by id and other constraints we can do it like this:

JavaScript

Or if you want to use a jpa query in your ParentRepository:

JavaScript

You can substitute the childs field and entities with your entities.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement