I have a service layer that Autowires a repository like so
@Service
public class OrderService {
@Autowired
private OrderRepository repository;
public List<Order> retrieveOrders(String storeId) {
try {
return repository.getOrders(storeId)
} catch(Exception e) {
...
}
}
}
I have new requirement that, depending on the store number, the repository query logic should change. I'm thinking of abstracting my repository and using a factory pattern. The current repository is an interface and extends JpaRepository; further more all of its functions are using @Query annotation to define the JPQL. This is an example with just one function, but there are several functions in my actual Repository
public interface OrderRepository extends JpaRepository {
@Query("select o " +
" from Orders o " +
" where o.storeId = :storeId")
public List<Order> getOrders(@Param(value = "storeId") String storeId);
}
The new requirements state that for a specific storeId, the SQL needs to change to something like this:
public interface OrderRepositoryStore886 extends JpaRepository {
@Query("select o " +
" from Order o " +
" where o.storeId = :storeId " +
" and o.status IN (1,3,10,15) " +
" and EXISTS (SELECT c from CollabOrder WHERE c.orderId = o.orderId)")
public List<Order> getOrders(@Param(value = "storeId") String storeId);
}
However all remaining stores should use the first SQL query.
I am trying to figure out how to conditionally @Autowire the repository based on storeId. I was thinking of creating a factory but I don't know how to make a factory that returns interface objects (I am still fairly new to java, this might be trivial but I've yet to figure it out). And if I try to turn the Repository interface into a class, it forces me to Override all of the abstract JpaRepository methods which is unnecessary extra code.