说明:
${ew.sqlSelect}
拼接select SQL主体
${ew.sqlSet}
拼接update SQL主体
${ew.sqlSegment}
拼接where后的语句
${ew.customSqlSegment}
拼接where后的语句(包括where。需注意在动态SQL中勿处于<where></where>标签内)
演示:
Mapper接口
@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
List<User> queryAll(@Param("tableName") String tableName,@Param(Constants.WRAPPER) Wrapper wrapper);
boolean updateById(@Param("tableName") String tableName,@Param("id") int id,@Param(Constants.WRAPPER) Wrapper wrapper);//若变量名为ew则无需注解
}
XML
<select id="queryAll" resultType="cn.alan.mybatis.POJO.User">
select ${ew.sqlSelect} from ${tableName} ${ew.customSqlSegment};
</select>
<update id="updateById">
update ${tableName} set ${ew.sqlSet} ${ew.customSqlSegment};
</update>
Controller(或Test)
@Autowired
UserServiceImpl userService;
@RequestMapping("/query")
public List<User> queryAll(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select("*").eq("age","10");
return userService.queryAll("user",wrapper);
//return userService.queryAll("user", Wrappers.query().select("*").eq("age","10"));
}
@RequestMapping("/update")
public boolean upDateById(){
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.set("name","5").eq("id","5");
return userService.updateById("user",5,wrapper);
//return userService.updateById("user",5,Wrappers.update().set("name","5").eq("id",5));
}
}
注:关于wrapper的写法都是正确的,但后者需要注意使用的是静态类Wrappers
等效select SQL:select * from user where age = 10;
等效update SQL:update user set name = 5 where id = 5;