There are 2 ways to implement mybatis dynamic sql.
1: script tag
@Select("<script> " + "SELECT id, name, email,password " + "FROM user " + " <where> " + " <if test=\"email != null\">id=#{email}</if> " + " <if test=\"name != null\"> AND name=#{name}</if> " + " </where> " + " </script> ")
At the same time, LIKE cannot be used directly, which can be implemented with the help of the concat function.
@Select("SELECT name from user WHERE email LIKE concat(#{prefix},'%') limit 5")
2 Use complex annotation classes. Such as: @InsertProvider, @UpdateProvider, @DeleteProvider and @SelectProvider, these are to create dynamic languages and let MyBatis execute these languages.
Now let's look at an example of how to use @SelectProvider to create a simple SELECT map. Create a TutorDynaSqlProvider. Java class with a findTutorByIdSql() method.
package com.owen.mybatis.sqlproviders; import org.apache.ibatis.jdbc.SQL; public class TutorDynaSqlProvider { public String findTutorByIdSql(int tutorId) { return "SELECT TUTOR_ID AS tutorId, NAME, EMAIL FROM TUTORS WHERE TUTOR_ID=#{tutorId}"; } }
@SelectProvider(type=TutorDynaSqlProvider.class, method="findTutorByIdSql") Tutor findTutorById(int tutorId);
refer to:
wrote