Hello everyone!
This is my first time posting here, so please don’t be too harsh on me
I’m trying to fetch some data from my DB and the entities I’m trying to fetch are in a m-t-m relationship.
The entities are Service.java and ServiceProvider.java. The Service entity is the owning and the ServiceProvider is the non-owning side. Now, when I create a new Service to write to a database, and connect with preexisting ServiceProvider and when I return the Service to check what has been inserted, everything is looking great. The data is correctly nested, the serviceProvider array is filled with the data I need, but when I try to @Get
the service with id:1 (any id, doesn’t matter) I get the serviceDescription
field, the service id but the serviceProviders
are ALWAYS empty…Even though the join table is correctly populated, the return value of my @Get
method is always missing that set of serviceProviders…
For example:
For this url/API (ignore the nonconventional writing):
http://localhost:8080/getService/1
← 1 is id of service
I get this response:
{
"id": 1,
"serviceDescription": "Default service description1",
"serviceProviders": []
}
Instead of:
{
"id": 1,
"serviceDescription": "Default service description1",
"serviceProviders": [
{
"id": 1,
"providerName": "provider1",
"services":[]
},
{
"id":2,
"providerName": "provider2",
"services":[]
}
{
"id":3
"providerName": "provider3",
"services":[]
}
]
}
This is the method I’m using to fetch the data…I’m even trying to force the Hibernate to load the data by trying to access the serviceProviders via the Services, but to no avail…
I thought maybe the id fields were a mismatch so I renamed them to fit the join table service_id
and service_provider_id
but still nothing was being fetched…
The method in question:
public Service findByID(long id){
Optional<Service> service = serviceRepository.findById(id);
service.ifPresent(s -> {
s.getServiceProviders().size();
});
System.out.println(service);
return service.orElse(null);
}
Please help because I’m out of ideas…
Thanks in advance