前言
本篇文章主要介绍的是SpringBoot整合mybatis-plus,实现增删改查。
GitHub源码链接位于文章底部。
建库建表
创建springboot数据库,创建t_user表,字段id主键自增,name,age。
工程结构
添加依赖
新建一个maven项目,在pom文件中添加以下依赖
<!--父级依赖,它用来提供相关的 Maven 默认依赖。
使用它之后,常用的springboot包依赖可以省去version 标签
配置UTF-8编码,指定JDK8-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath ></relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mysql 连接驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!--mybatis和mybatisplus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--自动生成getter/setter插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<!-- 模板引擎 代码生成器使用-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<resources>
<!--允许maven创建xml文件,否则xml要放在resources里-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
yml配置文件
server:
port: 8080
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8
mybatis-plus:
mapper-locations: classpath:com/lxg/springboot/dao/mybatisplus/mapper/xml/*Mapper.xml
typeAliasesPackage: com.lxg.springboot.dao.mybatisplus
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID,"该类型为未设置主键类型,5, "字符串全局唯一ID"";
id-type: 0
db-column-underline: true
refresh-mapper: true
#configuration:
#这个配置会将执行的sql打印出来,在开发或测试的时候可以用
#log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
主程序入口,启动类:
@SpringBootApplication
//配置mapper文件位置
@MapperScan("com.lxg.springboot.dao.mybatisplus.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
代码生成器
public class CodeGenerator{
/**
* @param args
* @Title: main
* @Description: 根据数据库生成表格
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
//代码存放地址
gc.setOutputDir( "D://code4" );
gc.setFileOverride( true );
// 不需要ActiveRecord 特性的请改为false
gc.setActiveRecord( false );
// XML 二级缓存
gc.setEnableCache( false );
// XML ResultMap
gc.setBaseResultMap( true );
// XML columList
gc.setBaseColumnList( false );
// 作者
gc.setAuthor( "LXG" );
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setControllerName( "%sController" );
gc.setServiceName( "%sService" );
gc.setServiceImplName( "%sServiceImpl" );
gc.setMapperName( "%sMapper" );
gc.setXmlName( "%sMapper" );
mpg.setGlobalConfig( gc );
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType( DbType.MYSQL );
dsc.setDriverName( "com.mysql.jdbc.Driver" );
dsc.setUsername( "root" );
dsc.setPassword( "root" );
dsc.setUrl( "jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL = false&serverTimezone = UTC" );
mpg.setDataSource( dsc );
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// 此处可以修改为您的表前缀
strategy.setTablePrefix( new String[]{"t_"} );
// 表名生成策略
strategy.setNaming( NamingStrategy.underline_to_camel );
// 需要生成的表
strategy.setInclude( new String[]{"t_user"} );
strategy.setSuperServiceClass( null );
strategy.setSuperServiceImplClass( null );
strategy.setSuperMapperClass( null );
mpg.setStrategy( strategy );
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent( "com.lxg.springboot.dao.mybatisplus" );
pc.setController( "controller" );
pc.setService( "service" );
pc.setServiceImpl( "service/serviceImpl" );
pc.setMapper("mapper");
pc.setEntity( "entity" );
pc.setXml( "xml" );
mpg.setPackageInfo( pc );
// 执行生成
mpg.execute();
}
}
MybatisPlus配置,包括分页插件、打印SQL,打印SQL的代码只为了测试开发阶段使用,生产环境需要注释掉,否则日志文件过大。
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* 打印 sql
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor =new PerformanceInterceptor();
//格式化sql语句
Properties properties =new Properties();
properties.setProperty("format", "false");
performanceInterceptor.setProperties(properties);
return performanceInterceptor;
}
}
实体类
@TableName("t_user")
@Data
public class User implements Serializable {
/** id */
private String id;
/** 姓名 */
private String name;
/** 年龄 */
private Integer age;
}
dao层
在mapper文件夹下创建UserMapper,继承BaseMapper
@Repository
public interface UserMapper extends BaseMapper<User> {
/**
* 方法名与映射文件的id一致
*/
List<User> findByXml();
}
mapper文件夹下创建xml文件夹,存放mapper映射文件,新建UserMapper.xml
<!--对应Mapper的位置-->
<mapper namespace="com.lxg.springboot.dao.mybatisplus.mapper.UserMapper">
<!--这里的id与Mapper中对应的方法名一致-->
<select id="findByXml" resultType="User">
select * from t_user;
</select>
</mapper>
service层
在service文件夹下创建UserService
public interface UserService {
/**
* 新增
*
* @param user
*/
public void addUser(User user);
/**
* 修改
* @param user
*/
public void updateUser(User user);
/**
* 根据id删除
* @param id
*/
public void deleteUser(String id) ;
/**
* 查询所有
*/
public List<User> findAll();
/**
* 根据id查询
* @param id
*/
public User findUserById(String id);
/**
* 条件查询+age排序
* @param
*/
public List<User> findSearch(Map searchMap);
/**
* 条件+分页+age排序
*/
public PageResult<User> findSearch(Map searchMap, int page, int size);
/**
* 通过Xml映射文件查询
*/
public List<User> findByXml();
}
在service文件夹下创建impl文件夹,存放实现类,在impl文件夹下创建UserServiceImpl实现类,实现UserService接口
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void addUser(User user) {
userMapper.insert(user);
}
@Override
public void updateUser(User user) {
userMapper.updateById(user);
}
@Override
public void deleteUser(String id) {
userMapper.deleteById(id);
}
@Override
public List<User> findAll() {
return userMapper.selectList(null);
}
@Override
public User findUserById(String id) {
return userMapper.selectById(id);
}
@Override
public List<User> findSearch(Map searchMap) {
EntityWrapper<User> wrapper = createSearchCondition(searchMap);
//根据age倒序查询
wrapper.orderBy(true, "age", false);
return userMapper.selectList(wrapper);
}
@Override
public PageResult<User> findSearch(Map searchMap, int page, int size) {
EntityWrapper<User> wrapper = createSearchCondition(searchMap);
//根据age倒序查询
wrapper.orderBy(true, "age", false);
Page<User> userPage = new Page<>(page,size);
List<User> list = userMapper.selectPage(userPage, wrapper);
return new PageResult<>(userPage.getTotal(),list);
}
@Override
public List<User> findByXml() {
return userMapper.findByXml();
}
/**
* 构造查询条件
* @param searchMap
* @return
*/
public EntityWrapper<User> createSearchCondition(Map searchMap) {
EntityWrapper<User> wrapper = new EntityWrapper<>(new User());
if (searchMap.get("name") != null) {
wrapper.eq("name", searchMap.get("name"));
}
if (searchMap.get("age") != null) {
wrapper.eq("age", searchMap.get("age"));
}
return wrapper;
}
}
controller层
在controller文件夹下创建UserController
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 新增
* @param user
*/
@RequestMapping(method = RequestMethod.POST)
public Result addUser(@RequestBody User user) {
userService.addUser(user);
return new Result(true, StatusCode.OK,"新增成功");
}
/**
* 根据id修改
* @param user
*/
@RequestMapping(method = RequestMethod.PUT)
public Result updateUser(@RequestBody User user) {
if (user.getId() == null || user.getId().equals("")) {
return new Result(false, StatusCode.ERROR,"无id,更新失败");
}
userService.updateUser(user);
return new Result(true, StatusCode.OK,"更新成功");
}
/**
* 根据id删除
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Result delete(@PathVariable String id) {
userService.deleteUser(id);
return new Result(true, StatusCode.OK,"删除成功");
}
/**
* 查询所有
*/
@RequestMapping(method = RequestMethod.GET)
public List<User> findAllUser() {
return userService.findAll();
}
/**
* 根据id查询
* @param id
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Result findByUserId(@PathVariable String id) {
return new Result(true, StatusCode.OK,"查询成功",userService.findUserById(id));
}
/**
* 条件查询
*/
@RequestMapping(value="/search",method = RequestMethod.POST)
public Result findSearch(@RequestBody Map searchMap){
return new Result(true,StatusCode.OK,"查询成功 ",userService.findSearch(searchMap));
}
/**
* 条件+分页
* @param searchMap
* @param page
* @param size
*/
@RequestMapping(value = "/search/{page}/{size}",method = RequestMethod.POST)
public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size){
return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap,page,size));
}
/**
* 通过Xml查询成功
* @return
*/
@RequestMapping(value = "/findByXml",method = RequestMethod.GET)
public Result findByXml(){
return new Result(true,StatusCode.OK,"XML查询成功",userService.findByXml());
}
}
整合durid连接池
pom文件中增加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
这种形式只需要在yml配置文件中增加一些配置即可,不用再写配置类了。
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8
type: com.alibaba.druid.pool.DruidDataSource
druid:
#初始化连接池大小
initial-size: 5
#配置最小连接数
min-idle: 5
#配置最大连接数
max-active: 20
#配置连接等待超时时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
#配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 300000
#测试连接
validation-query: SELECT 1 FROM DUAL
#申请连接的时候检测,建议配置为true,不影响性能,并且保证安全
test-while-idle: true
#获取连接时执行检测,建议关闭,影响性能
test-on-borrow: false
#归还连接时执行检测,建议关闭,影响性能
test-on-return: false
#是否开启PSCache,PSCache对支持游标的数据库性能提升巨大,oracle建议开启,mysql下建议关闭
pool-prepared-statements: true
#开启poolPreparedStatements后生效
max-pool-prepared-statement-per-connection-size: 20
#配置扩展插件,常用的插件有=>stat:监控统计 log4j:日志 wall:防御sql注入
filters: stat,wall,slf4j
#打开mergeSql功能;慢SQL记录
connection-properties: druid.stat.mergeSql\\=true;druid.stat.slowSqlMillis\\=5000
#配置DruidStatFilter
web-stat-filter:
enabled: true
url-pattern: "/*"
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
#配置DruidStatViewServlet
stat-view-servlet:
url-pattern: "/druid/*"
#IP白名单(没有配置或者为空,则允许所有访问)
allow: 127.0.0.1,192.168.163.1
#IP黑名单 (存在共同时,deny优先于allow)
deny: 192.168.1.73
# 禁用html页面上的“Reset All”功能
reset-enable: false
#登录名
login-username: root
#登录密码
login-password: root
启动程序后,访问localhost:8080/druid ,输入配置的账号密码即可登录可视化监控界面。
测试
参考https://www.lxgblog.com/article/1572258314 文章末测试部分
本文GitHub源码:https://github.com/lixianguo5097/springboot/tree/master/springboot-mybatisPlus
CSDN:https://blog.csdn.net/qq_27682773
简书:https://www.jianshu.com/u/e99381e6886e
博客园:https://www.cnblogs.com/lixianguo
个人博客:https://www.lxgblog.com