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, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');


  1. 导入依赖
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.5</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <!-- 3.5.4开始,支持 Spring Boot3 使用此版本 -->
        <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
        <version>3.5.5</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>


  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<ConfigurationCustomizer> 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> T selectOne(String statement) {
        return this.sqlSessionProxy.selectOne(statement);
    }

    public <E> List<E> 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<? extends DataSource> 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 对象进行自定义配置。

/**
 * 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<String, Cache> caches;
    protected final Map<String, ResultMap> resultMaps;
    protected final Map<String, ParameterMap> parameterMaps;
    protected final Map<String, KeyGenerator> keyGenerators;
    protected final Map<String, XNode> sqlFragments;
    protected final Map<String, MappedStatement> 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<? extends Log> logImpl;
    protected Class<? extends VFS> vfsImpl;
    protected Class<?> defaultSqlProviderType;
    protected LocalCacheScope localCacheScope;
    protected JdbcType jdbcTypeForNull;
    protected Set<String> 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<String, MappedStatement> mappedStatements;
    protected final Map<String, Cache> caches;
    protected final Map<String, ResultMap> resultMaps;
    protected final Map<String, ParameterMap> parameterMaps;
    protected final Map<String, KeyGenerator> keyGenerators;
    protected final Set<String> loadedResources;
    protected final Map<String, XNode> sqlFragments;
    protected final Collection<XMLStatementBuilder> incompleteStatements;
    protected final Collection<CacheRefResolver> incompleteCacheRefs;
    protected final Collection<ResultMapResolver> incompleteResultMaps;
    protected final Collection<MethodResolver> incompleteMethods;
    protected final Map<String, String> 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<User> {
}

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

public interface BaseMapper<T> extends Mapper<T> {

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

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

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

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

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

    // 分页查询记录
    default <P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> 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);
    }
}

你好!要在Spring Boot中整合MyBatis-Plus,你可以按照以下步骤进行操作: 步骤1:添加依赖 在你的Spring Boot项目的pom.xml文件中,添加MyBatis-Plus的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> ``` 请确保将`最新版本号`替换为MyBatis-Plus最新的版本号。 步骤2:配置数据源 在application.properties(或application.yml)文件中,配置数据库连接信息,例如: ```yaml spring.datasource.url=jdbc:mysql://localhost:3306/db_example spring.datasource.username=db_username spring.datasource.password=db_password spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 请将`db_example`、`db_username`和`db_password`分别替换为你的数据库名称、用户名和密码。 步骤3:创建实体类和Mapper接口 创建对应的实体类,并使用`@TableName`注解指定数据库表名。然后创建Mapper接口,继承自`BaseMapper`。 ```java import com.baomidou.mybatisplus.annotation.TableName; @TableName("user") public class User { private Long id; private String username; private String email; // getters and setters } ``` ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface UserMapper extends BaseMapper<User> { } ``` 步骤4:编写Service和Controller层代码 在Service层中,可以通过注入Mapper对象来使用MyBatis-Plus提供的便捷方法。例如: ```java import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.selectById(id); } // 其他业务逻辑方法 } ``` 在Controller层中,可以直接调用Service层的方法来处理请求。例如: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class UserController { @Resource private UserService userService; @GetMapping("/users/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } // 其他请求处理方法 } ``` 这样,你就完成了Spring Boot与MyBatis-Plus整合。你可以根据自己的需求,使用MyBatis-Plus提供的便捷方法来进行数据库操作。 希望对你有所帮助!如果还有其他问题,请继续提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值