mybatis-plus整合springboot入门
1、mybatis-plus快速入门
2、springboot整合mybatis-plus
(1)、映入maven依赖
<!--mybaitsi-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1.tmp</version> </dependency>
备注:springboot版本:2.2.6.RELEASE
(2)、yml文件数据库和mybatis-plus配置
#数据库配置 spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/mybaits-plus?useUnicode=true&characterEncoding=UTF-8&useSSL=false&nullCatalogMeansCurrent=true&serverTimezone=Asia/Shanghai #mybatis-plus配置 logging: level: com: example: demo: mapper: debug mybatis-plus: mapper-locations: classpath*:mappers/*.xml # 实体扫描,多个package用逗号或者分号分隔 type-aliases-package: com.example.demo.model configuration: # 驼峰下划线转换 map-underscore-to-camel-case: true cache-enabled: false call-setters-on-nulls: true global-config: # 刷新mapper 调试神器 refresh: true banner: false #数据库大写下划线转换 #capital-mode: true #序列接口实现类配置 #key-generator: com.baomidou.springboot.xxx # 数据库相关配置 db-config: db-type: mysql # 主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID"; id-type: AUTO # 字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断" field-strategy: not_empty capital-mode: true #逻辑删除配置 logic-delete-value: 1 logic-not-delete-value: 0
(3)、数据准备
CREATE TABLE `user` ( `id` bigint(11) NOT NULL COMMENT ‘主键ID‘, `name` varchar(30) NOT NULL COMMENT ‘姓名‘, `age` int(11) NOT NULL COMMENT ‘年龄‘, `email` varchar(50) NOT NULL COMMENT ‘邮箱‘, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES (‘1‘, ‘Jone‘, ‘18‘, ‘‘); INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES (‘2‘, ‘Jack‘, ‘20‘, ‘‘); INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES (‘3‘, ‘Tom‘, ‘28‘, ‘‘); INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES (‘4‘, ‘Sandy‘, ‘21‘, ‘‘); INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES (‘5‘, ‘Billie‘, ‘24‘, ‘‘); CREATE TABLE `course` ( `id` bigint(20) NOT NULL, `course` varchar(10) NOT NULL, `user_id` bigint(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `mybaits-plus`.`course` (`id`, `course`, `user_id`) VALUES (‘1‘, ‘语文‘, ‘2‘);
(4)、创建实体类
@Data public class User implements Serializable { private static final long serialVersionUID = -5817579076869802231L; private Long id; private String name; private Integer age; private String email; }
(5)、service层和dao层
public interface UserService extends IService<User> { PageInfo<User> selectPage(int pageNo, int pageSize, User user); PageInfo<User> selectPageCustom(int pageNo, int pageSize, User user); PageInfo<Map<String, Object>> selectPageCustomMap(int pageNo, int pageSize); }
@Service public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService { @Resource private UserMapper userMapper; @Override public PageInfo<User> selectPage(int pageNo, int pageSize, User user) { Page<User> page = new Page<>(pageNo,pageSize,false); QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("name",user.getName()); wrapper.orderByAsc("id"); page = userMapper.selectPage(page, wrapper); return new PageInfo<>(page); } @Override public PageInfo<User> selectPageCustom(int pageNo, int pageSize, User user) { Page<User> page = new Page<>(pageNo,pageSize); userMapper.pageMyQuery(page,user.getName()); return new PageInfo<>(page); } @Override public PageInfo<Map<String, Object>> selectPageCustomMap(int pageNo, int pageSize) { Page<Map<String, Object>> page = new Page<>(pageNo,pageSize); page = userMapper.pageMyMapQuery(page); return new PageInfo<>(page); }
public interface UserMapper extends BaseMapper<User> { Page<User> pageMyQuery(Page<User> pageInfo, @Param("name") String name); Page<Map<String,Object>> pageMyMapQuery(Page pageInfo); }
mapper文件
<?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.example.demo.mapper.UserMapper"> <select id="pageMyQuery" parameterType="User" resultType="User"> select id,name,age from user where name = #{name} </select> <select id="pageMyMapQuery" resultType="map"> SELECT * FROM course c LEFT JOIN `user` u on c.id = u.id </select> </mapper>
(6)、单元测试
@SpringBootTest @RunWith(SpringRunner.class) public class MybatisPlusTest { @Autowired private UserService userService; /** * 全局id生成器 */ @Autowired private DefaultIdentifierGenerator defaultIdentifierGenerator; /** * list查询 */ @Test public void selectList(){ List<User> list = userService.list(); Assert.assertEquals(6, list.size()); list.forEach(System.out::println); } /** *单条插入 */ @Test public void inset(){ User user = new User(); user.setName("张三"); user.setAge(20); user.setEmail(""); user.setId(defaultIdentifierGenerator.nextId(user)); userService.save(user); } /** * 批量插入 */ @Test public void saveBatch(){ List<User> list = new ArrayList<>(); User user1 = new User(); user1.setName("王五"); user1.setAge(20); user1.setEmail(""); user1.setId(defaultIdentifierGenerator.nextId(user1)); list.add(user1); User user2 = new User(); user2.setName("李四"); user2.setAge(20); user2.setEmail(""); user2.setId(defaultIdentifierGenerator.nextId(user1)); list.add(user2); userService.saveBatch(list); } /** * 按照id集合删除 */ @Test public void delBatch(){ List<Long> ids = new ArrayList<>(); ids.add(1259742998092120066L); ids.add(1259749231041806337L); userService.removeByIds(ids); } /** * 分页查询 */ @Test public void queryPage(){ User user = new User(); user.setName("李四"); PageInfo<User> userPageInfo = userService.selectPage(1,3,user); System.err.println(userPageInfo); } /** * 自定义分页查询返回T */ @Test public void queryPageCustom(){ User user = new User(); user.setName("李四"); PageInfo<User> userPageInfo = userService.selectPageCustom(1,3,user); System.err.println(userPageInfo); } /** * 自定义分页查询返回map */ @Test public void queryPageCustomMap(){ PageInfo<Map<String,Object>> userPageInfo = userService.selectPageCustomMap(1,3); System.err.println(userPageInfo); }
补充:PageInfo源码(自定义分页实体类)
@Datapublic class PageInfo<T> { /** * 当前页 */ private Long pageNo; /** * 每页显示条数 */ private Long PageSize; /** * 总条数 */ private Long total; /** * 结果集 */ private List<T> result; public PageInfo(Page<T> page) { this.pageNo = page.getCurrent(); this.PageSize = page.getSize(); this.total = page.getTotal(); this.result = page.getRecords(); }}
mybatis-plus配置类
@Configurationpublic class MybatisPlusConfig { /** * 全局id生成器 * @return */ @Bean public DefaultIdentifierGenerator identifierGenerator(){ return new DefaultIdentifierGenerator(); } /** * 分页插件 * @return */ @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; }}
相关推荐
CoderToy 2020-11-16
技术之博大精深 2020-10-16
emmm00 2020-11-17
bianruifeng 2020-11-16
云中舞步 2020-11-12
世樹 2020-11-11
暗夜之城 2020-11-11
张荣珍 2020-11-12
amienshxq 2020-11-14
ASoc 2020-11-14
yungpheng 2020-10-19
loveyouluobin 2020-09-29
尘封飞扬 2020-09-29
Coder技术文摘 2020-09-29
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09