This post will take you through a several examples of creating a dynamic sql queries which you will come up in a day to day development using mybatis.
We can use the if statement where we need to conditionally include parts of a where clause.
eg: Search Employee. Employee name and role can be added as filter fields.
- Use of choose, when, otherwise
What about switch statement in query where we need to choose only one case among many options.
When you have a query with multiple optional where clauses you may find a difficulty to build the query with correct prefix. MyBatis has a simple solution for this. It is where element. The where element knows to only insert "WHERE" if there is any content returned by the containing tags. Furthermore, if that content begins with "AND" or "OR", it knows to strip it off.
The set element can be used to dynamically include columns to update, and leave out others.
Another common necessity for dynamic SQL is the need to iterate over a collection, often to build an IN condition.