springboot 集成mybatis plus3

时间:2023-12-15 20:15:08

gradle:

compile group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.0.1'

 

MybatisPlusConfig.java
import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringUtils; import javax.sql.DataSource; //Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.abcv.*.mapper.*")
public class MybatisPlusConfig { /**
* 分页插件
*/
@Bean(name = "pagination")
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
} }

 

ApplicationStart.java springboot启动增加对spring文件的加载
@ImportResource("classpath:/META-INF/spring/*.xml")

  spring配置文件:

	<context:annotation-config />
<context:component-scan base-package="com.abcv" /> <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="plugins" >
<list>
<ref bean="pagination"/>
</list>
</property>
</bean>

  因为dataSource、pagination都是通过spring注册的,所以mybatis plus的sessionfactory需要手动注入

如果mybatis plus分页无效,首先检查有没有配置分页插件,即上面的MybatisPlusConfig类

其次是如果自定义了sqlSessionFactory,还要将其注册进sqlSessionFactory