web123456

MybatisPlus' Sql injector

We already know that in MP,AbstractSqlInjectorWillBaseMapperThe methods in it are injected into the Mybatis container so that these methods can be executed normally.

Then, if we need to expandBaseMapperHow to implement the methods in this article?

Let’s learn from the extension findAll method as an example.

1. Write MyBaseMapper

  1. /*
  2. General mapper interface. When creating other mapper interfaces in the future, the BaseMapper will no longer be inherited, but MyBaseMapper will be inherited.
  3. */
  4. public interface MyBaseMapper<T> extends BaseMapper<T> {
  5. /*
  6. Query all users
  7. */
  8. public List<User> findAll();
  9. }

OthersMapperAll can inherit the mapper, thus achieving unified extension.

like:

  1. public interface UserMapper extends MyBaseMapper<User> {
  2. /*
  3. Custom findById method
  4. */
  5. public User findById(Long id);
  6. }

2. Write MySqlInjector

If you inherit the AbstractSqlInjector directly, the original BaseMapper method will be invalid, so we choose to inherit.DefaultSqlInjectorExpand.

  1. /*
  2. Custom sql injector
  3. */
  4. public class MySqlInjector extends DefaultSqlInjector {
  5. @Override
  6. public List<AbstractMethod> getMethodList() {
  7. List<AbstractMethod> methodList = super.getMethodList();
  8. // Expand custom methods
  9. (new FindAll());
  10. return methodList;
  11. }
  12. }

3. Write FindAll

  1. public class FindAll extends AbstractMethod {
  2. @Override
  3. public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
  4. String sql = "select * from " + ();
  5. SqlSource sqlSource = (configuration, sql, modelClass);
  6. return this.addSelectMappedStatement(mapperClass, "findAll", sqlSource, modelClass, tableInfo);
  7. }
  8. }

4. Register to Spring Container

  1. /*
  2. Custom sql injector
  3. */
  4. @Bean
  5. public MySqlInjector mySqlInjector(){
  6. return new MySqlInjector();
  7. }

5. Test

  1. @Test
  2. public void testFindAll(){
  3. List<User> users = this.();
  4. for (User user : users) {
  5. (user);
  6. }
  7. }

The output SQL:

[main] []-[DEBUG] ==> Preparing: select
* from tb_user
[main] []-[DEBUG] ==> Parameters:
[main] []-[DEBUG] <== Total: 10

At this point, we have achieved global expansionSQL Injectionutensil.