Generic DAO search method

930 Views Asked by At

I have a scenario in which there are two entity classes. Their structures are like

Class A{
Long id;
// some fields
}

Class B{
Long id;
Long associtedA;
// some field
}

The field associtedA in entity B refers to A.id The relation between them is A one-to-many B

I need to get the list of A and with them related B data list.

I tried to implement this using search. But I am not able to find some working solution. Also I cannot change the entity.

I can implement this by retrieving all the A list then for each A.id again retrieving related B data. But for that I have to make service call in loop, which is something I don't want.

Is there any smart way to this scenario?

2

There are 2 best solutions below

0
Jannik Weichert On

You might want to take a look at JinQ (http://www.jinq.org) Then you could do:

streamProvider.streamAll(entityManager, B.class).join((a, source) -> source.stream(A.class)
.where(pair -> pair.getOne().id == pair.getTwo().id)
.select(pair -> pair.getOne())
.toArray()

Think this is the smartest way ;) (Of course you would need Java 8 for Lambda Expressions)

0
Calabacin On

Sorry, these entities seem to be wrong. Are you using JPA? An entity manager?

If you are using an entity manager (such as Hibernate for example) Class B would be something like this:

Class B{
  Long id;
  A associtedA;
  // some field
}

See that B.associtedA is of type A.