Mybatis Plus是原始Mybatis的增强,框架内部自动实现了Mapper的CRUD操作,极大的提高了编程效率。对单表操作基本无需编写Mapper.xml文件内容,对复杂的多表关联查询时,需要额外在Mapper.xml编写对应的sql语句。
Spring整合Mybatis Plus 和前文Spring整合Mybatis 步骤基本类似,具体步骤如下:
1、增加项目依赖【pom.xml】
重点依赖说明:spring-context是spring的核心、AOP需要aspectjweaver支持,事务管理器需要spring-jdbc,mybatis-plus框架,druid是数据源
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.20.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
</dependencies>
2、spring和mybatis配置文件配置【applicationContext.xml、mybatis-config.xml】
重点配置介绍:
- component-scan 注解扫描的包
- dataSource 数据源配置
- sessionFactory 用到了mybatis plus的核心类MybatisSqlSessionFactoryBean,交给spring IOC容器管理生成,里面包含mybatis的配置文件、mapper接口的xml实现文件和分页插件
- MapperScannerConfigurer mapper 接口扫描包,如项目中的StudentMapper
- transactionManager 定义事务管理器
- tx:annotation-driven 开启事务注解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.text"/>
<!--MyBatis plus与Spring的整合配置 -->
<!--数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://xxx:3306/xxx?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="xxx"/>
<property name="password" value="xxx"/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>
<!--SessionFactoryBean-->
<bean id="sessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- MyBaitsPlus3.4以后版本配置分页插件-->
<property name="plugins">
<array>
<bean class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
<property name="interceptors">
<list>
<bean class="com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor"/>
</list>
</property>
</bean>
</array>
</property>
</bean>
<!--配置Mapper扫描器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.text.mapper"/>
</bean>
<!--定义事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 驼峰命名转换 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
3、定义数据库实体、Mapper接口及对应的mapper.xml文件
以简单的学生表、课程表为例
CREATE TABLE `student` (
`id` varchar(100) COLLATE utf8mb4_bin NOT NULL,
`name` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL,
`age` int DEFAULT NULL,
`course_id` varchar(100) COLLATE utf8mb4_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
CREATE TABLE `course` (
`id` varchar(100) COLLATE utf8mb4_bin NOT NULL,
`name` varchar(100) COLLATE utf8mb4_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
java实体:@TableName("student") 标识和数据库的对应关系,如果字段已经是驼峰命名,则不需要在属性字段上标识@TableField
package com.text.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("student")
public class Student {
private String id;
private String name;
private int age;
private String courseId;//课程id
}
package com.text.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("course")
public class Course {
private String name;//课程名称
private String id;//课程id
}
Dto类:对于复杂查询的sql结果,根据查询的结果集字段新建一个dto类,下方的StudentDto对于下方mapper.xml文件中的resultType="com.text.entity.StudentDto"
package com.text.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentDto {
private String id;
private String name;
private int age;
private String courseId;//课程id
private String courseName;//课程名称
}
Mapper接口【StudentMapper.java】:
重点代码说明:@Param("minAge") Integer minAge 注解标识的参数名就是下方mapper.xml文件
#{}识别的字段名,Integer类型就是mapper.xml文件中的parameterType
package com.text.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.text.entity.Student;
import com.text.entity.StudentDto;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
IPage<StudentDto> selectStudentMap(IPage page,@Param("minAge") Integer minAge);
}
Mapper.xml文件【student.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.text.mapper.StudentMapper">
<select id="selectStudentMap" parameterType="Integer" resultType="com.text.entity.StudentDto">
select s.* ,c.name as courseName from student s left join course c on s.course_id = c.id where s.age >= #{minAge}
</select>
</mapper>
4、服务接口及实现【StudentService.java、StudentServiceImpl.java】
package com.text.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.text.entity.Student;
import com.text.entity.StudentDto;
public interface StudentService {
void batchInsert() throws Exception;
IPage<Student> getByPage(long pageNum, long pageSize) throws Exception;
IPage<StudentDto> getStudentInfoByPage(long pageNum, long pageSize,int minAge) throws Exception;
}
package com.text.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.text.entity.Student;
import com.text.entity.StudentDto;
import com.text.mapper.StudentMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Transactional(rollbackFor = Exception.class)
@Service
public class StudentServiceImpl implements StudentService{
@Resource
private StudentMapper studentMapper;
@Override
public void batchInsert() throws Exception {
for(int i=10;i<20;i++) {
if(i==13) {
throw new Exception("模拟抛出异常");
}
Student student = new Student(i+"","张三"+i,i,"1");
studentMapper.insert(student);
}
}
@Override
public IPage<Student> getByPage(long pageNum, long pageSize) throws Exception {
IPage<Student> page = new Page<>(pageNum,pageSize);
QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",10);
page = this.studentMapper.selectPage(page, queryWrapper);
return page;
}
@Override
public IPage<StudentDto> getStudentInfoByPage(long pageNum, long pageSize,int minAge) throws Exception {
IPage<StudentDto> page = new Page<>(pageNum,pageSize);
page = this.studentMapper.selectStudentMap(page,minAge);
return page;
}
public StudentMapper getStudentMapper() {
return studentMapper;
}
public void setStudentMapper(StudentMapper studentMapper) {
this.studentMapper = studentMapper;
}
}
5、测试类及运行结果
package com.text;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.text.entity.Student;
import com.text.entity.StudentDto;
import com.text.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Application {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
StudentService studentService = context.getBean("studentServiceImpl", StudentService.class);
//studentService.batchInsert();
IPage<Student> page = studentService.getByPage(1, 5);
List<Student> records = page.getRecords();
System.out.println(records);
long total = page.getTotal();
System.out.println("total:" + total);
System.out.println("============");
IPage<StudentDto> page2 = studentService.getStudentInfoByPage(1, 5,18);
List<StudentDto> records2 = page2.getRecords();
System.out.println(records2);
long total2 = page2.getTotal();
System.out.println("total2:" + total2);
}
}
从运行结果可以看出,分页查询时,先查询了总记录数,再查询了分页的数据