Database table org_structure stores an organizational structure nested hierarchy. It starts from the root (CEO) which has parent_id NULL.
id
title
parent_id
1
CEO
NULL
2
Director 1
1
3
Director 2
1
4
Manager 1
2
5
Manager 2
2
6
Manager 3
3
7
Manager 4
3
8
OP 1
4
9
OP 2
4
10
OP 3
5
11
OP 4
5
12
OP 5
6
13
OP 6
6
14
OP 7
7
15
OP 8
7
This is a graphical representation of org_structure database table.
Let us take an example that we want to select “Director 2” and every descendant in the hierarchy. So result will include (Director 2, Manager 3, Manager 4, OP 5 – 8).
MariaDB provides elegant solution for this problem (recursive queries).
1
2
3
4
5
6
7
8
9
10
11
with recursive res(id,title)as(
select id,title
from org_structure
where id=3
union all
select os.id,os.title
from org_structure os
inner join res
on os.parent_id=res.id
)
select *from res;
Result:
3 Director 2 6 Manager 3 7 Manager 4 12 OP 5 13 OP 6 14 OP 7 15 OP 8
Suppose that you have a webshop with a credit card payment option. Credit card payments work fine in a production environment. There is a new requirement to implement a sandbox environment for the webshop. Sandbox environment doesn’t charge your credit card. It always returns a successful response.
Each checkout implementation is based on the following CheckoutService interface:
However, we want to instantiate either BankCheckoutService or SandboxCheckoutService based on the variable in the application properties file. SandboxCheckoutService should be instantiated if application properties contains the following content:
1
sandbox=true
If sandbox the variable is false BankCheckoutService will be instantiated.
Spring Boot already has a solution. @ConditionalOnProperty annotation provides us the possibility to conditionally instantiate bean based on property value from application.properties file.
The controller doesn’t have to be changed since it expects CheckoutService interface which is implemented in both BankCheckoutService and SandboxCheckoutService. Controller depends on abstraction not implementation as it is specified in SOLID principle.
We can now switch between BankCheckoutService and SandboxCheckoutService by changing the sandbox variable in the application.properties file.