1

I have a database relation which looks like this (in reality it looks slightly different but I removed unimportant fields):

Table Customer (
ID      NUMBER(13),
...
)

Table Orders (
ID      NUMBER(13),
BUYER_ID      NUMBER(13),
SELLER_ID     NUMBER(13),
...
)

Both BUYER_ID and SELLER_ID are references to CUSTOMER table. And in my situation there are cases that BUYER_ID and SELLER_ID might be the same for an order (I know it sounds funny).

My question is: if I am asking for a specific order using jpa repository, with both buyer and seller being the same customer, is this query optimized to return the same object? Or is the customer table asked twice for the same object?

The background of this question is that my team wants to add a flag in order table which would indicate weather the buyer and seller are the same (to optimize the query) but I believe that this is already optimized with springboot. Unfortunately I cannot find confirmation for this anywhere :(

Saeda
  • 11
  • 1
  • Please show your entity mapping – Simon Martinelli Nov 08 '21 at 10:42
  • 1
    Spring Boot nor Spring Data JPA optimizes anything. They are just abstractions over JPA. JPA translates a JPA query into SQL, if you write SQL nothing will be optimized. For JPA it might, but don't count on it. – M. Deinum Nov 08 '21 at 10:46
  • 1
    You might want to look at Hibernate First level cache for documentaiton on this if I understand your question right. See https://stackoverflow.com/questions/337072/what-are-the-first-and-second-level-caches-in-nhibernate . Beware though that the devil is in the detail, you probably write some queries in such a way that the cache does not kick in (e.g. directly write a query with a join for each buyer / seller). Agreed that "optimizing" is not the word for it - but the implementation might skip some DB fetches if they already happened in a cohesive "scope" / unit of work. – GPI Nov 08 '21 at 10:48

0 Answers0