CQRS is an Architectural pattern which solves complexity issues in larger projects. CQRS simplifies your service layer by dividing into main two blocks. Most people confusing about this pattern but it is simple.
- What is a Command – Command is basically a CRUD without R , that means CUD, simple right? CUD – CREATE, UPDATE, DELETE. Commands are database transaction operations, for example you are going to change the state of your database by editing, inserting or deleting a record or set of records.
- What is a Query – Query is R in CRUD, means RETRIEVE. Queries are fetching database records and they are not deal with transaction stuff.
Is this pattern something you should try?
Yes but “Use Responsibly”, This may increase the complexity of small projects but ideal if you need clean separation between commands and queries.
What technologies we should use for this
In Spring Ecosystem, ideally an ORM aka any JPA technology works for command implementation since they optimized to persist any complex objects. but I recommend Spring Data JPA Crud repository over plain Hibernate since Spring Data CRUD is well optimized and can do almost all the CRUD operations. If you have really complex DB architecture use Hibernate with Spring Data.
For Queries we can use MyBatis. Hibernate would attempt to load the entire object graph and you’d need to start tuning queries with LazyLoading tricks to keep it working on a large domain. This is important when running complex analytic queries that don’t even return entity objects. Hibernate only offers SqlQuery and bean Transformers in this case with huge default types like BigDecimal, while myBatis could easily map to a simple POJO non-entity (https://softwareengineering.stackexchange.com/questions/158109/what-are-the-advantages-of-mybatis-over-hibernate). If you want to just fetch information, use myBatis.
Technically, that’s how you gonna separate the two components, you can find simple implementation from below repository.
In above example there are two end-points for Query and Command
Command – http://localhost:8081/doc/upload/Salary [POST]
Query – http://localhost:8081/doc/download/Salary/1 [GET]
First end-point is multipart file upload end-point and it will persist the CSV content to the table and it is a CREATE operation. I have used JPA for this operation.
Second end-point is for retrieve data from the DB by documentID. I have used MyBatis for this operation.