bookmark_borderMariaDB recursive query

Database table org_structure stores an organizational structure nested hierarchy. It starts from the root (CEO) which has parent_id NULL.

idtitleparent_id
1CEONULL
2Director 11
3Director 21
4Manager 12
5Manager 22
6Manager 33
7Manager 43
8OP 14
9OP 24
10OP 35
11OP 45
12OP 56
13OP 66
14OP 77
15OP 87

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).

Result:

3 Director 2
6 Manager 3
7 Manager 4
12 OP 5
13 OP 6
14 OP 7
15 OP 8

Detailed explanation can be found on following link:
https://mariadb.com/kb/en/recursive-common-table-expressions-overview/

bookmark_borderSpring boot dependency injection using @ConditionalOnProperty annotation

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:

The implementation of CheckoutService an interface for the production environment is BankCheckoutService

CheckoutController gets instance of CheckoutService using @Autowired annotation (dependency injection).

Let us create a new implementation of CheckoutService interface for the sandbox environment:

It will work fine if we replace a constructor of CheckoutController to get SandboxCheckoutService bean:

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:

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.

BankCheckoutService:

SandboxCheckoutService

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.