本文使用springboot+mybatis-plus+mysql搭建的开发环境:
集成mybatis-plus插件之后我们就可以省去一些基本的crud操作,有更多的时间去处理核心业务逻辑
1:pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.itmck</groupId>
<artifactId>mybatis-plus-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis-plus-demo</name>
<description>Spring Boot unint mybatis-plus</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
<!--apache工具类-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2:application.properties配置
server.port=8089
server.servlet.context-path=/mck
##spring.profiles.active=dev
##datasource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/spring_db?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
###--------------------mybatis-plus配置文件---------------------
##1扫描mapper.xml文件
mybatis-plus.mapper-locations=classpath*:/mybatis/mapper/*.xml
##2配置别名
mybatis-plus.type-aliases-package=com.itmck.pojo
##关闭控制台mybatis-plus的logo
mybatis-plus.global-config.banner=false
##配置打印sql在控制台
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
测试类如下
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisPlusDemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
@Test
public void testSelect2() {
System.out.println(("----- selectByPage method test ------"));
//使用分页之前,必须先制定分页插件,否则分页无法使用
//1-----------制定分页插件
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setDialectType("mysql");//设置使用mysql作为分页
//2-----------设置分页参数
Page<User> userPage = new Page<>();
userPage.setCurrent(1);
userPage.setSize(5);
//3----------------查询
IPage<User> userIPage = userMapper.selectPage(userPage, null);//SELECT id,name,email,age FROM user LIMIT ?,?
List<User> records = userIPage.getRecords();
for (User record : records) {
System.out.println("======================="+record);
}
}
@Test
public void testInsert() {
System.out.println(("----- insert method test ------"));
User user = new User();
user.setName("wxp123");
user.setAge(24);
user.setEmail("956411425@qq.com");
int i=0;
while (i<5){
int insert = userMapper.insert(user);//INSERT INTO user ( id, name, email, age ) VALUES ( ?, ?, ?, ? )
i++;
}
}
@Test
public void testUpdate() {
System.out.println(("----- update method test ------"));
User user = new User();
user.setName("mck");
user.setAge(24);
user.setEmail("347451331@qq.com");
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("id", 1173108471533436929L);
/**
* 参数1:新的值
*/
int update = userMapper.update(user, userQueryWrapper);//UPDATE user SET name=?, email=?, age=? WHERE (id = ?)
Assert.assertEquals(1, update);
if (update == 1){
System.out.println("update成功");
}else{
System.out.println("update失败");
}
}
@Test
public void testDelete(){
System.out.println(("----- delete method test ------"));
// int i = userMapper.deleteById(1173113442471559170L);//删除一个 DELETE FROM user WHERE id=?
// Assert.assertEquals(1, i);
// HashMap<String, Object> map = new HashMap<>();
// map.put("name", "wxp");
// int i1 = userMapper.deleteByMap(map);//DELETE FROM user WHERE name = ?
ArrayList<Long> longs = new ArrayList<>();
longs.add(1173108471533436929L);
longs.add(1173113442471559171L);
int i = userMapper.deleteBatchIds(longs);//批量删除 DELETE FROM user WHERE id IN ( ? , ? )
Assert.assertEquals(2, i);
}
@Test
public void findAllByPage(){
PageParam mySqlPage = new PageParam();
mySqlPage.setCurrentPage(2);
mySqlPage.setLimit(5);
System.out.println("offset:"+mySqlPage.getOffset());
List<User> list = userMapper.findAllByPage(mySqlPage);
for (User user : list) {
System.out.println("------------"+user);
}
}
}
4:UserMapper如下:
定义mapper继承extends BaseMapper< T > ,这样就可使用已经封装好的crud方法
/**
* Create by it_mck 2019/9/14 20:58
*
* @Description: 使用Mybatis-plus通用mapper
* @Version: 1.0
*/
@Repository
@Mapper//扫描注解
public interface UserMapper extends BaseMapper<User> {
User findById(@Param("id") Long id);
/**
* 分页
* @param pageParam
* @return
*/
List<User> findAllByPage(PageParam pageParam);
}
//--------------------------下面是在使用mysql的时候进行分页的-----------
public class PageParam {
private int currentPage;//当前页
private int limit;
private int offSet;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
//只要使用给page和limit赋值,那么offset自动计算出来
public int getOffset() {
this.offSet = (currentPage - 1) * limit;
return offSet;
}
}
5:UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.itmck.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.itmck.pojo.User">
<id column="id" property="id" jdbcType="BIGINT" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="email" property="email" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List">
id, name, age,email
</sql>
<select id="findById" resultType="com.itmck.pojo.User" parameterType="java.lang.Long">
select * from user where id=#{id}
</select>
<select id="findAllByPage" resultType="com.itmck.pojo.User" parameterType="com.itmck.base.utils.PageParam">
SELECT * FROM user limit #{offSet},#{limit}
</select>
</mapper>
总结:上面就是使用mybatis-plus.基本框架代码结构如下: