2021-03-12-MyBatis Dynamic SQL

MyBatis

  • MyBatis is a semi-automatic mapping framework. It is called semi-automatic because it needs to manually match the provided POJO, SQL, and mapping relationship, while Hibernate only needs to provide the POJO and mapping relationship.

Dynamic SQL

  • Dynamic SQL is mainly used to solve the situation of uncertain query conditions: during the running of the program, query according to the query conditions submitted by the user. The submitted query conditions are different, and the executed SQL statements are different. If each possible situation is listed one by one, and all the conditions are permuted and combined, a large number of SQL statements will appear. At this time, dynamic SQL can be used to solve such problems.
    That is, the conditions are judged through various tags provided by MyBatis to realize dynamic splicing of SQL statements.

If

  • Requirement: We are now doing user inquiries, it is possible to bring a user name, and there may be no
    Insert picture description here
  • When querying, give a value that does not give username to observe the result

where

Insert picture description here

trim

  • The role of replacement
Attributes description
prefix The prefix for splicing SQL statements
suffix Suffix for splicing sql statement
prefixOverrides Remove the keyword or character in front of the sql statement. The keyword or character is specified by the prefixOverrides attribute. If the attribute is specified as "AND", when the beginning of the sql statement is "AND", the trim tag will remove the "AND"
suffixOverrides Remove the keywords or characters after the SQL statement, the keywords or characters are specified by the suffixOverrides attribute

Insert picture description here

choose、when、otherwise

  • When multiple query conditions appear at the same time, sort the priority
    If …elseif…else
    Insert picture description here

Set

  • If a table has multiple fields, but I only need to update the fields that need to be updated to reduce network bandwidth
    Insert picture description here

foreach

  • Case, we do batch delete or update
    Method one, in the form of an integer array
    Insert picture description here
  • Method 2: by way of collection
    Insert picture description here
  • Way three: by way of map
    Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41270550/article/details/113928762