- 准备数据
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');
- 导入依赖
<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>
- 查看源码可知 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;
- 配置
# 配置数据源
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);
}
}
- 编码
在 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;
}
}
- 开始使用
@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);
}
}