Mybatis-Plus是一个Mybatis的增强工具,在Mybatis的基础上只做增强不做改变,能提高开发效率
创建Mysql表,如下所示:
mysql> create table user (
-> id bigint(20) auto_increment not null comment '主键ID',
-> name varchar(30) null default null comment '姓名',
-> age int(11) null default null comment '年龄',
-> email varchar(50) null default null comment '邮箱',
-> primary key (id)
-> );
Query OK, 0 rows affected, 2 warnings (0.01 sec)
mysql>
添加测试数据,如下所示:
mysql> insert into 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]');
Query OK, 5 rows affected (0.04 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql>
com.baomidou
mybatis-plus-boot-starter
3.5.2
引入了mybatis-plus-boot-starter,就不用引入mybatis-spring-boot-starter依赖了,因为所有功能都能实现
可以看到自动添加了mybatis、mybatis-spring、spring-boot-starter-jdbc依赖
查看mybatis-plus-boot-starter-3.5.2.jar的META-INF\spring.factories,可以看到给我们自动配置了IdentifierGeneratorAutoConfiguration、MybatisPlusLanguageDriverAutoConfiguration、MybatisPlusAutoConfiguration
# Auto Configure
org.springframework.boot.env.EnvironmentPostProcessor=\
com.baomidou.mybatisplus.autoconfigure.SafetyEncryptProcessor
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.baomidou.mybatisplus.autoconfigure.IdentifierGeneratorAutoConfiguration,\
com.baomidou.mybatisplus.autoconfigure.MybatisPlusLanguageDriverAutoConfiguration,\
com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
现在我们重点来看MybatisPlusAutoConfiguration类,可以看到:
package com.baomidou.mybatisplus.autoconfigure;
......省略部分......
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({MybatisPlusProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisPlusLanguageDriverAutoConfiguration.class})
public class MybatisPlusAutoConfiguration implements InitializingBean {
......省略部分......
@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();
return executorType != null ? new SqlSessionTemplate(sqlSessionFactory, executorType) : new SqlSessionTemplate(sqlSessionFactory);
}
......省略部分......
public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {
......省略部分......
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
if (!AutoConfigurationPackages.has(this.beanFactory)) {
MybatisPlusAutoConfiguration.logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
} else {
MybatisPlusAutoConfiguration.logger.debug("Searching for mappers annotated with @Mapper");
......省略部分......
}
......省略部分......
}
......省略部分......
}
......省略部分......
}
查看MybatisPlusProperties配置类,如下所示:
mybatis-plus.mapper-locations
进行配置......省略部分......
@ConfigurationProperties(
prefix = "mybatis-plus"
)
public class MybatisPlusProperties {
......省略部分......
private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};
......省略部分......
private Properties configurationProperties;
@NestedConfigurationProperty
private MybatisConfiguration configuration;
......省略部分......
}
说明如下:
package com.hh.springboottest.myController;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@TableName("user")
@Data
public class User {
// 以下不是数据库表对应字段
@TableField(exist = false)
private Integer noUseField1;
@TableField(exist = false)
private String noUseField2;
//以卜是数据库表对应字段
@TableId(value = "id", type = IdType.AUTO) // 需要表设置主键自增
private Long id;
private String name;
private Integer age;
private String email;
}
向SpringBoot启动类,添加@MapperScan注解,指定Mapper接口的全路径位置。如下所示:
package com.hh.springboottest;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.hh.springboottest.mapper")
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
UserMapper继承了BaseMapper接口
package com.hh.springboottest.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hh.springboottest.myController.User;
import org.springframework.stereotype.Repository;
@Repository // 可以不加。不加@Autowired时IDEA会提示不能注入
public interface UserMapper extends BaseMapper {
}
BaseMapper接口实现了很多操作数据库的默认方法,所以很多方法不用我们自己实现了。如下所示:
UserService接口继承了Iservice接口,IService接口有很多方法。如下所示:
package com.hh.springboottest.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hh.springboottest.myController.User;
public interface UserService extends IService {
}
UserServiceImpl实现类继承了ServiceImpl,并且指定了UserMapper和User类,这样UserServiceImpl就拥有了UserMapper的方法了。如下所示:
package com.hh.springboottest.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.springboottest.mapper.UserMapper;
import com.hh.springboottest.myController.User;
import com.hh.springboottest.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
}
对表数据进行其他的crud操作
package com.hh.springboottest;
import com.hh.springboottest.myController.User;
import com.hh.springboottest.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@Slf4j
@SpringBootTest
public class MyApplicationTest {
@Autowired
UserService userService;
@Test
public void dataOperateTest() {
User user = userService.getById(1L);
List users1 = userService.list();
boolean isDeleted = userService.removeById(1L);
log.info("删除数据:{}", isDeleted ? "成功" : "失败");
}
}
运行测试程序,结果如下:
......省略部分......
2022-11-19 21:41:40.432 INFO 4244 --- [ main] com.hh.springboottest.MyApplicationTest : 删除数据:成功
2022-11-19 21:41:40.450 INFO 4244 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
2022-11-19 21:41:40.454 INFO 4244 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed