1、pom文件引入依赖
引入MyBatis-Plus之后请不要再次引入MyBatis以及mybatis-spring-boot-starter和MyBatis-Spring,以避免因版本差异导致的问题
<!--引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 mybatis-spring-boot-starter和MyBatis-Spring,以避免因版本差异导致的问题--><!--<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>${spring-boot.mybatis}</version></dependency>--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>${mybatis-plus.version}</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-annotation</artifactId><version>${mybatis-plus.version}</version></dependency>
2、DataSourceConfig.java
数据源
package cn.xxx.coupon.pay.config;import javax.sql.DataSource;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;@Configuration
public class DataSourceConfig {@Primary@ConfigurationProperties(prefix = "spring.datasource.druid.one")@Bean(name = "dsOne")public DataSource dsOne() {return DruidDataSourceBuilder.create().build();}@ConfigurationProperties(prefix = "spring.datasource.druid.two")@Bean(name = "dsTwo")public DataSource dsTwo() {return DruidDataSourceBuilder.create().build();}}
3、MybatisPlusConfigOne.java
配置mybatis-plus第一个数据库的SqlSessionFactory和SqlSessionTemplate
package cn.xxx.coupon.pay.config;import javax.sql.DataSource;import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;@Configuration
@MapperScan(basePackages = "cn.xxx.coupon.pay.mapper.dsOne", sqlSessionFactoryRef = "dsOneSqlSessionFactory", sqlSessionTemplateRef = "dsOneSqlSessionTemplate")
public class MybatisPlusConfigOne {@Bean(name = "dsOneSqlSessionFactory")public SqlSessionFactory dsOneSqlSessionFactory(@Qualifier("dsOne") DataSource datasource) throws Exception {MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();// 设置mybatis的xml所在位置// bean.setMapperLocations(new// PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db2/*.xml"));// configuration配置bean// MybatisConfiguration configuration = new MybatisConfiguration();// configuration.setMapUnderscoreToCamelCase(true); //数据库字段下划线到Java的驼峰的映射,默认true// configuration.setCacheEnabled(true); //是否支持mybatis的二级缓存,默认true// 配置打印sql语句// configuration.setLogImpl(StdOutImpl.class);// 添加自定义配置// bean.setConfiguration(configuration);// 设置datasourcebean.setDataSource(datasource);// 插件对象MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();// 分页插件mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));bean.setPlugins(mybatisPlusInterceptor);return bean.getObject();}@Bean(name = "dsOneSqlSessionTemplate")public SqlSessionTemplate dsOneSqlSessionTemplate(@Qualifier("dsOneSqlSessionFactory") SqlSessionFactory sessionFactory) {return new SqlSessionTemplate(sessionFactory);}
}
4、MybatisPlusConfigTwo.java
配置mybatis-plus第二个数据库的SqlSessionFactory和SqlSessionTemplate
package cn.xxx.coupon.pay.config;import javax.sql.DataSource;import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;@Configuration
@MapperScan(basePackages = "cn.xxx.coupon.pay.mapper.dsTwo", sqlSessionFactoryRef = "dsTwoSqlSessionFactory", sqlSessionTemplateRef = "dsTwoSqlSessionTemplate")
public class MybatisPlusConfigTwo {@Bean(name = "dsTwoSqlSessionFactory")public SqlSessionFactory dsTwoSqlSessionFactory(@Qualifier("dsTwo") DataSource datasource) throws Exception {MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();// 设置mybatis的xml所在位置// bean.setMapperLocations(new// PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db2/*.xml"));// configuration配置bean// MybatisConfiguration configuration = new MybatisConfiguration();// configuration.setMapUnderscoreToCamelCase(true); //数据库字段下划线到Java的驼峰的映射,默认true// configuration.setCacheEnabled(true); //是否支持mybatis的二级缓存,默认true// 配置打印sql语句// configuration.setLogImpl(StdOutImpl.class);// 添加自定义配置// bean.setConfiguration(configuration);// 设置datasourcebean.setDataSource(datasource);// 插件对象MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();// 分页插件mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));bean.setPlugins(mybatisPlusInterceptor);return bean.getObject();}@Bean(name = "dsTwoSqlSessionTemplate")public SqlSessionTemplate dsTwoSqlSessionTemplate(@Qualifier("dsTwoSqlSessionFactory") SqlSessionFactory sessionFactory) {return new SqlSessionTemplate(sessionFactory);}
}
5、@MapperScan和dao层@Mapper二选一
6、定义接口类BranchInfoMapper.java
package cn.xxx.coupon.pay.mapper.dsTwo;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import cn.xxx.coupon.pay.dto.commodity.BranchInfo;public interface BranchInfoMapper extends BaseMapper<BranchInfo> {}
7、测试代码MybatisPlusTest.java
package cn.xxx.coupon.pay.test.coupon;import java.util.List;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.xxx.coupon.pay.PreCouponPayApplication;
import cn.xxx.coupon.pay.dto.commodity.BranchInfo;
import cn.xxx.coupon.pay.mapper.dsTwo.BranchInfoMapper;@SpringBootTest(classes = PreCouponPayApplication.class)
public class MybatisPlusTest {@Autowiredprivate BranchInfoMapper branchInfoMapper;@Testpublic void testSelectList() {System.out.println(("----- selectAll method test ------"));List<BranchInfo> branchInfos = branchInfoMapper.selectList(null);branchInfos.forEach(System.out::println);}@Testpublic void testSelectOne() {System.out.println(("----- selectOne method test ------"));QueryWrapper<BranchInfo> queryWrapper = new QueryWrapper<>();queryWrapper.eq("storecode", "012999");queryWrapper.eq("issue_id", "80501");BranchInfo branchInfo = branchInfoMapper.selectOne(queryWrapper);System.out.println(branchInfo);}@Testpublic void testSelectPage() {QueryWrapper<BranchInfo> queryWrapper = new QueryWrapper<>();Page<BranchInfo> page = new Page<>(2, 30);Page<BranchInfo> branchInfoPage = branchInfoMapper.selectPage(page, queryWrapper);System.out.println("当前页:" + branchInfoPage.getCurrent());System.out.println("每页记录数:" + branchInfoPage.getSize());System.out.println("总记录数:" + branchInfoPage.getTotal());System.out.println("总页数:" + branchInfoPage.getPages());List<BranchInfo> branchInfoList = branchInfoPage.getRecords();branchInfoList.forEach(System.out::println);}
}
8、问题1:启动日志会打印两遍mybatis-plus的logo
_ _ |_ _ _|_. ___ _ | _
| | |\/|_)(_| | |_\ |_)||_|_\ / | 3.5.5 _ _ |_ _ _|_. ___ _ | _
| | |\/|_)(_| | |_\ |_)||_|_\ / | 3.5.5
9、问题2:eclipse里mybatis-plus自动提示显示中文乱码
Window -> Preferences -> General -> Workspace,找到Text file encoding,设置为UTF-8,保存重启eclipse
10、小结mybatis-plus使用方式
方式一:
自定义xxxMapper接口并继承BaseMapper接口,提供默认方法
方式二:
用IService接口,提供默认方法
(1)自定义xxxService接口并继承IService
(2)自定义接口实现类xxxServiceImpl,并继承ServiceImpl,并实现xxxService接口
IBranchInfoService.java
package cn.xxx.coupon.pay.mapper.service;import com.baomidou.mybatisplus.extension.service.IService;import cn.xxx.coupon.pay.dto.commodity.BranchInfo;/*** 在自己定义的service接口当中继承IService接口*/
public interface IBranchInfoService extends IService<BranchInfo> {}
IBranchInfoServiceImpl.java
package cn.xxx.coupon.pay.mapper.service.Impl;import org.springframework.stereotype.Service;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.xxx.coupon.pay.dto.commodity.BranchInfo;
import cn.xxx.coupon.pay.mapper.dsTwo.BranchInfoMapper;
import cn.xxx.coupon.pay.mapper.service.IBranchInfoService;/*** 在接口实现impl当中继承ServiceImpl,实现自己的接口*/
@Service
public class IBranchInfoServiceImpl extends ServiceImpl<BranchInfoMapper, BranchInfo> implements IBranchInfoService {}
方式三:
复杂sql在mapper中用@Select、@Update、@Insert、@Delete自定义sql语句
BranchInfoMapper.java
package cn.xxx.coupon.pay.mapper.dsTwo;import org.apache.ibatis.annotations.Select;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import cn.xxx.coupon.pay.dto.commodity.BranchInfo;public interface BranchInfoMapper extends BaseMapper<BranchInfo> {@Select("select storecode, locname, loctype, supzone, supzonename, afbmerchantid, issue_id from t_afb_branchinfo where storecode = #{storeCode} and issue_id = #{issueId}")public BranchInfo selectBranchInfoByStoreCode(String storeCode, String issueId);
}
方式四:
复杂sql在mapper中使用@SelectProvider、@UpdateProvider、@InsertProvider、@DeleteProvider注解结合对应的Provider类,以及动态sql注解来实现动态生成sql语句
方式五:
是方式二和方式三的结合,在自定义接口实现类xxxServiceImpl调用mapper类里写好的方法。外部只调用service类不调用mapper类
11、测试类
package cn.xxx.coupon.pay.test.coupon;import java.util.List;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.xxx.coupon.pay.PreCouponPayApplication;
import cn.xxx.coupon.pay.dto.commodity.BranchInfo;
import cn.xxx.coupon.pay.mapper.dsTwo.BranchInfoMapper;
import cn.xxx.coupon.pay.mapper.service.IBranchInfoService;@SpringBootTest(classes = PreCouponPayApplication.class)
public class MybatisPlusTest {@Autowiredprivate BranchInfoMapper branchInfoMapper;@Autowiredprivate IBranchInfoService iBranchInfoService;@Testpublic void testSelectList() {System.out.println(("----- selectAll method test ------"));List<BranchInfo> branchInfos = branchInfoMapper.selectList(null);branchInfos.forEach(System.out::println);}/*** >:gt* =:eq* <:lt* >=:ge* <=:le*/@Testpublic void testSelectOne() {System.out.println(("----- selectOne method test ------"));QueryWrapper<BranchInfo> queryWrapper = new QueryWrapper<>();queryWrapper.eq("storecode", "012999");queryWrapper.eq("issue_id", "80501");BranchInfo branchInfo = branchInfoMapper.selectOne(queryWrapper);System.out.println(branchInfo);}@Testpublic void testSelectPage() {QueryWrapper<BranchInfo> queryWrapper = new QueryWrapper<>();Page<BranchInfo> page = new Page<>(2, 30);Page<BranchInfo> branchInfoPage = branchInfoMapper.selectPage(page, queryWrapper);System.out.println("当前页:" + branchInfoPage.getCurrent());System.out.println("每页记录数:" + branchInfoPage.getSize());System.out.println("总记录数:" + branchInfoPage.getTotal());System.out.println("总页数:" + branchInfoPage.getPages());List<BranchInfo> branchInfoList = branchInfoPage.getRecords();branchInfoList.forEach(System.out::println);}@Testpublic void testSelectList2() {System.out.println(("----- selectAll method test2 ------"));List<BranchInfo> branchInfos = iBranchInfoService.list();branchInfos.forEach(System.out::println);}@Testpublic void testSelectOne2() {System.out.println(("----- selectOne method test2 ------"));BranchInfo branchInfo = branchInfoMapper.selectBranchInfoByStoreCode("012999", "80501");System.out.println(branchInfo);}}