0

Situation : (Using springs) I have a repository with two methods defined with custom queries

@Query("-----")
public Object getA();
@Query("-----")
public List<Object> getB();

For some reason I don't want to write a join query to retrieve the data,

In the controller I define an end point and in that I can call those methods for which I am able to retrieve the data,

But I would want something like this,

All objects of B should be inside the A Object.

A(Object)
a1:
a2:
a3:
B[3] :
  b1:
  b2:
  b3

How can I do this?

Kiran Joshi
  • 746
  • 1
  • 11
  • 27
  • 1
    First, you generally shouldn't be calling repository methods directly from your controller. This is what `@Service` is for. Second, if `A` has a relation to `B`, you should be using `@JoinTable` on a field of `A`, which would mean that fetching `A` (`@Query("select a from A a")`) would give you access to the associated `B`s. – beerbajay Jul 09 '15 at 10:16
  • Thank you beerbajay, The point is when I said "_For some reason_" I meant this, There are like 10 more entities which has dependency on A (OneToMany) I defined all of them, When I query for A, hibernate is querying for all possible dependencies and retrieving details which I don't want. I would want only A and B in this case. A and D in other case. – Kiran Joshi Jul 09 '15 at 10:33
  • 1
    By default `FetchType.LAZY` is used and your additional entities should not be fetched in their entirety. You also have the option of defining *multiple* mapped `@Entity`s for the same table, so one with all of `A`s fields and then only `B`. This is redundant and in most situations not a best practice, but maybe your use-case is one of these edge cases where it is acceptable (but probably not). – beerbajay Jul 09 '15 at 10:38
  • I understood what you are talking and I could achieve that using FetchType.LAZY. This is valid in case where two entities are related but there are situations where I need an object like I have shown and there would not be any relation between them. – Kiran Joshi Jul 09 '15 at 11:02
  • And Beerbajay, why use service to invoke repository methods? What are the advantages over it if I don't have any business logic to be applied. http://stackoverflow.com/questions/3688664/simple-spring-app-why-use-service-layer Can you add a real time scenario apart from theoretical explanation given in the above link. – Kiran Joshi Jul 09 '15 at 13:32

1 Answers1

1

Apart from writing a Service that wraps the Repository: Since it seems you are already using Spring Data, you could just write a custom query method, that combines both queries (http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behaviour).