pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>springbootgroupId>
<artifactId>springbootartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>springbootname>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.3.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.3.4version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.9version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-extensionartifactId>
<version>3.3.1version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-amqpartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-aopartifactId>
dependency>
dependencies>
project>
application.yml
spring:
profiles:
active: dev
application-dev.yml
server:
port: 8086
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml
type-aliases-package: org.spring.springboot.entity
#showSql
logging:
level:
com:
example:
mapper : debug
Person
package org.spring.springboot.entity;
import lombok.Data;
@Data
public class Person {
private Integer id;
private String userName;
private String passWord;
public Person() {
}
public Person(Integer id, String userName, String passWord) {
this.id = id;
this.userName = userName;
this.passWord = passWord;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
HelloController
package org.spring.springboot.controller;
import org.spring.springboot.entity.Person;
import org.spring.springboot.mapper.PersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HelloController {
/*Autowired默认的装配方式:byType;
Qualifier意思是合格者,一般跟Autowired配合使用,需要指定一个bean的名称,通过bean名称就能找到需要装配的bean。
@Autowired
@Qualifier("personMapper")
原理:
其实在启动spring IoC时,容器自动装载了一个AutowiredAnnotationBeanPostProcessor后置处理器,
当容器扫描到@Autowied、@Resource(是CommonAnnotationBeanPostProcessor后置处理器处理的)或@Inject时,
就会在IoC容器自动查找需要的bean,并装配给该对象的属性
*/
@Autowired
PersonMapper personMapper;
@RequestMapping("/test")
public void test(){
// 新增数据
Person person1 = new Person();
person1.setId(1);
person1.setPassWord("123456");
person1.setUserName("zhangsanfeng");
int i1 = personMapper.insert(person1);
System.out.println("插入一条数据>>>" + i1);
// 新增数据
Person person11 = new Person();
person11.setId(2);
person11.setPassWord("8888");
person11.setUserName("zhangsanfeng888");
int i11 = personMapper.insert(person11);
System.out.println("插入一条数据>>>" + i11);
// 修改数据
Person person2 = new Person();
person2.setId(1);
person2.setPassWord("789789");
int i2 = personMapper.updateById(person2);
System.out.println("更新一条数据>>>" + i2);
// 删除数据
int i3 = personMapper.deleteById(3);
System.out.println("删除一条数据>>>" + i3);
// 查询单条数据
Person person3 = personMapper.selectById(1);
System.out.println("查询1条数据>>>" + person3.toString());
// 查询多条数据
List<Person> person = personMapper.selectList(null);
System.out.println("查询多条数据>>>" + person);
}
//不同查询方式总结
@RequestMapping("/select")
public void test2(){
// 查询条件:名字中包含'王大锤888'
// 使用查询构造器,查询一条记录
QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
queryWrapper.like("user_name","王大锤888");
Person person = personMapper.selectOne(queryWrapper);
System.out.println(person);
// 使用lambda 条件构造器,查询一条记录
LambdaQueryWrapper<Person> queryWrappers = new QueryWrapper<Person>().lambda();
queryWrappers.like(Person::getUserName,"王大锤888");
Person person2 = personMapper.selectOne(queryWrappers);
System.out.println(person2);
//函数式编程方式,查询一条记录
Person person3 = new LambdaQueryChainWrapper<Person>(personMapper).like(Person::getUserName,"王大锤888").one();
System.out.println(person3);
//将对象直接以构造参数的形式传递给 QueryWrapper,MyBatisPlus 会自动根据实体对象中的属性自动构建相应查询的 SQL 语句
Person person4 = new Person();
person4.setUserName("王大锤888");
QueryWrapper<Person> queryWrapper4 = new QueryWrapper<>(person4);
// 开始查询
Person user = personMapper.selectOne(queryWrapper4);
System.out.println(user);
//通过 Map 封装的条件查询,返回一个 List
Map<String,Object> columnMap = new HashMap<>();
columnMap.put("user_name", "王大锤888");
List<Person> users = personMapper.selectByMap(columnMap);
System.out.println(users);
// 使用查询构造器,返回一个 List
QueryWrapper<Person> queryWrapper5 = new QueryWrapper<>();
queryWrapper5.like("user_name","王大锤888");
// 开始查询
List<Person> person5 = personMapper.selectList(queryWrapper5);
System.out.println(person5);
}
@RequestMapping("/selectByPage")
public IPage<Person> test3(){
// 查询条件:名字中包含'王大锤8'
LambdaQueryWrapper<Person> queryWrappers = new QueryWrapper<Person>().lambda();
queryWrappers.like(Person::getUserName,"王大锤8");
IPage<Person> page = personMapper.selectPage(new Page<>(1,2),queryWrappers);
return page;
}
@RequestMapping("/testByMap")
public IPage<Map<String, Object>> test4(){
// 查询条件:名字中包含'王大锤8'
LambdaQueryWrapper<Person> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(Person::getUserName,"王大锤8");
// 开始查询
IPage<Map<String, Object>> page = personMapper.selectMapsPage(new Page<>(1,2),
queryWrapper);
return page;
}
}
PersonMapper
package org.spring.springboot.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.spring.springboot.entity.Person;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface PersonMapper extends BaseMapper<Person> {
//Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
}
主启动类ApplicationApp
package org.spring.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// Spring Boot 应用的标识
/* UserMapper.java 如果不添加Mapper注解,则此处需要添加MapperScan
@MapperScan("com.example.mapper")
*/
@SpringBootApplication
public class ApplicationApp {
public static void main(String[] args) {
// 程序启动入口
// 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
SpringApplication.run(ApplicationApp.class,args);
}
}
MybatisPlusConfig
package org.spring.springboot.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
/**
* mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
查询条件:名字中包含’王大锤8’,查询第1页,每页显示2条
不添加MybatisPlusConfig类,查询结果没有分页
添加MybatisPlusConfig类,正常显示分页
public interface BaseMapper<T> {
//插入一条记录 参数:实体 返回:int
Integer insert(T entity);
//根据 ID 删除 参数:主键ID 返回:int
Integer deleteById(Serializable id);
//根据 columnMap 条件,删除记录 参数:表字段 map 对象 返回:int
Integer deleteByMap(@Param("cm") Map<String, Object> columnMap);
//根据 entity 条件,删除记录 参数:实体对象封装操作类(可以为 null) 返回:int
Integer delete(@Param("ew") Wrapper<T> wrapper);
//删除(根据ID 批量删除) 参数:主键ID列表 返回:int
Integer deleteBatchIds(List<? extends Serializable> idList);
//根据 ID 修改 参数:实体对象 返回:int
Integer updateById(T entity);
//根据 whereEntity 条件,更新记录 参数:实体对象,实体对象封装操作类(可以为 null) 返回:int
Integer update(@Param("et") T entity, @Param("ew") Wrapper<T> wrapper);
//根据 ID 查询 参数:主键ID 返回:T
T selectById(Serializable id);
//查询(根据ID 批量查询) 参数:主键ID列表 返回:List
List<T> selectBatchIds(List<? extends Serializable> idList);
//查询(根据 columnMap 条件) 参数:表字段 map 对象 返回:List
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
//根据 entity 条件,查询一条记录 参数:实体对象 返回:T
T selectOne(@Param("ew") T entity);
//根据 Wrapper 条件,查询总记录数 参数:实体对象 返回:int
Integer selectCount(@Param("ew") Wrapper<T> wrapper);
//根据 entity 条件,查询全部记录 参数:实体对象封装操作类(可以为 null) 返回:List
List<T> selectList(@Param("ew") Wrapper<T> wrapper);
//根据 Wrapper 条件,查询全部记录 参数:实体对象封装操作类(可以为 null) 返回:List
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> wrapper);
//根据 Wrapper 条件,查询全部记录 参数:实体对象封装操作类(可以为 null) 返回:List
List<Object> selectObjs(@Param("ew") Wrapper<T> wrapper);
/**
* 用法:(new RowBounds(offset, limit), ew);
* 根据 entity 条件,查询全部记录(并翻页)
* @param rowBounds
* 分页查询条件(可以为 RowBounds.DEFAULT)
* @param wrapper
* 实体对象封装操作类(可以为 null)
* @return List
*/
//根据 ID 删除 参数:主键ID 返回:int
List<T> selectPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);
/** -- 不常用,
* 根据 Wrapper 条件,查询全部记录(并翻页)
* @param rowBounds
* 分页查询条件(可以为 RowBounds.DEFAULT)
* @param wrapper
* 实体对象封装操作类
* @return List
//根据 ID 删除 参数:主键ID 返回:int
List<Map<String, Object>> selectMapsPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);
}
七、枚举类使用
UserGroupEnum
public class UserGroupEnum {
@Getter
@AllArgsConstructor
public enum userGroupTypeEnum{
STATIC("0","静态"),
DYNAMIC("1","动态")
;
private String type;
private String message;
}
}
单元测试
EnumTest
@SpringBootTest
public class EnumTest {
@Test
public void enumDataTest() {
String STATIC = UserGroupEnum.userGroupTypeEnum.STATIC.getType()+"_"+UserGroupEnum.userGroupTypeEnum.STATIC.getMessage();
String DYNAMIC = UserGroupEnum.userGroupTypeEnum.DYNAMIC.getType()+"_"+UserGroupEnum.userGroupTypeEnum.DYNAMIC.getMessage();
System.out.println(STATIC);
System.out.println(DYNAMIC);
}
}
参考文章
SpringBoot - MyBatis-Plus使用详解
Mybatis-Plus 的BaseMapper用法
Mybatis-Plus的BaseMapper的使用