SpringBoot3整合MyBatis-Plus

  1. 准备数据
CREATE TABLE `t_user`
(
    id BIGINT NOT NULL COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);

INSERT INTO `t_user` (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');


  1. 导入依赖

    org.springframework.boot
    spring-boot-starter-parent
    3.2.5
    



    
        org.springframework.boot
        spring-boot-starter-web
    
    
        com.baomidou
        
        mybatis-plus-spring-boot3-starter
        3.5.5
    
    
        com.mysql
        mysql-connector-j
    
    
        org.projectlombok
        lombok
        true
    


  1. 查看源码可知 MybatisPlusAutoConfiguration 已经为我们配置好了 SqlSessionFactory、SqlSessionTemplate 等组件。
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisPlusProperties.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisPlusLanguageDriverAutoConfiguration.class})
public class MybatisPlusAutoConfiguration implements InitializingBean {

    private final List configurationCustomizers;

    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSource);


    @Bean
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        ExecutorType executorType = this.properties.getExecutorType();
        if (executorType != null) {
            return new SqlSessionTemplate(sqlSessionFactory, executorType);
        } else {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

    @org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
    @Import(AutoConfiguredMapperScannerRegistrar.class)
    @ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})
    public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

        @Override
        public void afterPropertiesSet() {
            logger.debug(
                "Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.");
        }
    }

    private void applyConfiguration(MybatisSqlSessionFactoryBean factory) {
        MybatisPlusProperties.CoreConfiguration coreConfiguration = this.properties.getConfiguration();
        MybatisConfiguration configuration = null;
        if (coreConfiguration != null || !StringUtils.hasText(this.properties.getConfigLocation())) {
            configuration = new MybatisConfiguration();
        }
        if (configuration != null && coreConfiguration != null) {
            coreConfiguration.applyTo(configuration);
        }
        if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
            for (ConfigurationCustomizer customizer : this.configurationCustomizers) {
                customizer.customize(configuration);
            }
        }
        factory.setConfiguration(configuration);
    }
}

public class SqlSessionTemplate implements SqlSession, DisposableBean {
    private final SqlSessionFactory sqlSessionFactory;
    private final ExecutorType executorType;
    private final SqlSession sqlSessionProxy;
    private final PersistenceExceptionTranslator exceptionTranslator;

    public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
    }

    public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
        this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true));
    }

    public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
        Assert.notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
        Assert.notNull(executorType, "Property 'executorType' is required");
        this.sqlSessionFactory = sqlSessionFactory;
        this.executorType = executorType;
        this.exceptionTranslator = exceptionTranslator;
        this.sqlSessionProxy = (SqlSession)Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(), new Class[]{SqlSession.class}, new SqlSessionInterceptor());
    }

    public  T selectOne(String statement) {
        return this.sqlSessionProxy.selectOne(statement);
    }

    public  List selectList(String statement, Object parameter) {
        return this.sqlSessionProxy.selectList(statement, parameter);
    }

    private class SqlSessionInterceptor implements InvocationHandler {
        private SqlSessionInterceptor() {
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            SqlSession sqlSession = SqlSessionUtils.getSqlSession(SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator);

            Object unwrapped;
            try {
                Object result = method.invoke(sqlSession, args);
                if (!SqlSessionUtils.isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
                    sqlSession.commit(true);
                }

                unwrapped = result;
            } catch (Throwable var11) {
                unwrapped = ExceptionUtil.unwrapThrowable(var11);
                if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
                    SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
                    sqlSession = null;
                    Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException)unwrapped);
                    if (translated != null) {
                        unwrapped = translated;
                    }
                }

                throw (Throwable)unwrapped;
            } finally {
                if (sqlSession != null) {
                    SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
                }

            }

            return unwrapped;
        }
    }
}
    

@Data
@Accessors(chain = true)
@ConfigurationProperties(prefix = "mybatis-plus")
public class MybatisPlusProperties {

    private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

    // Location of MyBatis xml config file.
    private String configLocation;

    // Locations of MyBatis mapper files.
    private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};

    // Packages to search type aliases.
    private String typeAliasesPackage;

    @Getter
    @Setter
    public static class CoreConfiguration {
        private Boolean mapUnderscoreToCamelCase;
        private Boolean callSettersOnNulls;

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {

	private Class type;

	private String driverClassName;

	private String url;

	private String username;

	private String password;
    


  1. 配置
# 配置数据源
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/develop
    username: root
    password: 910199

# 以下配置也可以通过实现 ConfigurationCustomizer 接口对 MyBatis 的 Configuration 对象进行自定义配置
mybatis-plus:
  type-aliases-package: cn.xsu.boot.data.pojo		# 类型别名(typeAliases)
  configuration:
    map-underscore-to-camel-case: true	 # 开启驼峰命名自动映射
    call-setters-on-nulls: true		# 查询结果中包含空值的列,在映射的时候,不会映射这个字段

MyBatis-Plus 提供了一个 ConfigurationCustomizer 接口,允许我们在 MyBatis 的配置过程中进行自定义配置。通过实现这个接口,我们可以对 MyBatis 的 Configuration 对象进行自定义配置。

SpringBoot3整合MyBatis-Plus_第1张图片

/**
 * Callback interface that can be customized a {@link MybatisConfiguration} object generated on auto-configuration.
 */
@FunctionalInterface
public interface ConfigurationCustomizer {

    /**
     * Customize the given a {@link MybatisConfiguration} object.
     *
     * @param configuration the configuration object to customize
     */
    void customize(MybatisConfiguration configuration);
}
public class MybatisConfiguration extends Configuration { 
    private static final Log logger = LogFactory.getLog(MybatisConfiguration.class);
    protected final MybatisMapperRegistry mybatisMapperRegistry;
    protected final Map caches;
    protected final Map resultMaps;
    protected final Map parameterMaps;
    protected final Map keyGenerators;
    protected final Map sqlFragments;
    protected final Map mappedStatements;
    private boolean useGeneratedShortKey;
}
public class Configuration {
    protected Environment environment;
    protected boolean safeRowBoundsEnabled;
    protected boolean safeResultHandlerEnabled;
    protected boolean mapUnderscoreToCamelCase;
    protected boolean aggressiveLazyLoading;
    protected boolean multipleResultSetsEnabled;
    protected boolean useGeneratedKeys;
    protected boolean useColumnLabel;
    protected boolean cacheEnabled;
    protected boolean callSettersOnNulls;
    protected boolean useActualParamName;
    protected boolean returnInstanceForEmptyRow;
    protected boolean shrinkWhitespacesInSql;
    protected boolean nullableOnForEach;
    protected boolean argNameBasedConstructorAutoMapping;
    protected String logPrefix;
    protected Class logImpl;
    protected Class vfsImpl;
    protected Class defaultSqlProviderType;
    protected LocalCacheScope localCacheScope;
    protected JdbcType jdbcTypeForNull;
    protected Set lazyLoadTriggerMethods;
    protected Integer defaultStatementTimeout;
    protected Integer defaultFetchSize;
    protected ResultSetType defaultResultSetType;
    protected ExecutorType defaultExecutorType;
    protected AutoMappingBehavior autoMappingBehavior;
    protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior;
    protected Properties variables;
    protected ReflectorFactory reflectorFactory;
    protected ObjectFactory objectFactory;
    protected ObjectWrapperFactory objectWrapperFactory;
    protected boolean lazyLoadingEnabled;
    protected ProxyFactory proxyFactory;
    protected String databaseId;
    protected Class configurationFactory;
    protected final MapperRegistry mapperRegistry;
    protected final InterceptorChain interceptorChain;
    protected final TypeHandlerRegistry typeHandlerRegistry;
    protected final TypeAliasRegistry typeAliasRegistry;
    protected final LanguageDriverRegistry languageRegistry;
    protected final Map mappedStatements;
    protected final Map caches;
    protected final Map resultMaps;
    protected final Map parameterMaps;
    protected final Map keyGenerators;
    protected final Set loadedResources;
    protected final Map sqlFragments;
    protected final Collection incompleteStatements;
    protected final Collection incompleteCacheRefs;
    protected final Collection incompleteResultMaps;
    protected final Collection incompleteMethods;
    protected final Map cacheRefMap;

在 Spring Boot 容器中放入一个 ConfigurationCustomizer 组件并实现自定义配置。

@Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
            configuration.getTypeAliasRegistry().registerAliases("cn.xsu.boot.data.pojo");
            configuration.setMapUnderscoreToCamelCase(true);
        };
    }
}
@Configuration
public class MyBatisConfig implements ConfigurationCustomizer {

    @Override
    public void customize(MybatisConfiguration configuration) {
        configuration.getTypeAliasRegistry().registerAliases("cn.xsu.boot.data.pojo");
        configuration.setMapUnderscoreToCamelCase(true);
    }
}


  1. 编码

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 mapper 文件夹。

@MapperScan(value = "cn.xsu.boot.data.mapper")
@SpringBootApplication
public class SpringBootDataApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ioc = SpringApplication.run(SpringBootDataApplication.class, args);
        for (String name : ioc.getBeanDefinitionNames()) {
            System.out.println(name);
        }
    }
}

编写实体类 User:

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("t_user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

编写 mapper 包下的 UserMapper 接口:

public interface UserMapper extends BaseMapper {
}

BaseMapper 接口通常定义了一些基本的数据库操作方法:

public interface BaseMapper extends Mapper {

    // 插入一条记录到数据库中
    int insert(T entity);

    // 根据主键 ID 查询一条记录
    T selectById(Serializable id);

    // 根据主键 ID 删除一条记录
    int deleteById(Serializable id);

    // 根据主键 ID 更新一条记录
    int updateById(@Param("et") T entity);

    // 查询所有符合条件的记录列表
    List selectList(@Param("ew") Wrapper queryWrapper);

    // 分页查询记录
    default 

> P selectPage(P page, @Param("ew") Wrapper queryWrapper) { page.setRecords(this.selectList(page, queryWrapper)); return page; } }

  1. 开始使用
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @GetMapping("/user/{id}")
    public User findUserById(@PathVariable Long id) {
        return userService.queryUserById(id);
    }
}

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User queryUserById(Long id) {
        return userMapper.selectById(id);
    }
}

SpringBoot3整合MyBatis-Plus_第2张图片

你可能感兴趣的:(springboot,mybatis)