本文为博主原创,未经允许不得转载:
1.创建一个spring boot的工程应用:
File ---- > New ----->Project ----> 然后选中Spring Initializr 继续创建:
2.添加spring boot ,mybatis plus 以及 mysql 相关的依赖:
<dependencies> <!-- spring boot web启动 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </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> <!-- mysql 数据库连接 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- mybatis plus 代码生成器 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api --> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency> </dependencies>
3. spring boot 的配置文件中配置项目启动名称,端口号,数据库连接等:
此处需要注意的是:spring boot 项目的配置文件是application.properties ,不是bootstrap.yml,bootstrap.yml是spring cloud 中定义解析配置文件的格式
server.port=8002 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root
# mybatis plus 调用打印 sql mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
并启动项目,查看启动日志,会打印spring 以及 mybatis plus 的banner 图案
4.创建用户表,定义表结构如下:
CREATE TABLE `user` ( `id` bigint(20) NOT NULL COMMENT '主键ID', `name` varchar(30) DEFAULT NULL COMMENT '姓名', `age` int(11) DEFAULT NULL COMMENT '年龄', `email` varchar(50) DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf-8;
5. 业务代码:
5.1 创建实体类:
package com.example.demo.entity; import lombok.Data; import javax.persistence.Table; @Data @Table(name = "user") public class User { private Long id; private String name; private int age; private String email; }
5.2 创建 mapper,需要继承BaseMapper
mapper接口需要在项目启动时进行加载扫描,可以使用两种方式进行配置:
第一种可以使用 @Mapper注解,在每个mapper接口进行注解,第二种可以在启动类上使用 @MapperScan 注解,其中的值为mapper的包路径
其中@Repository 表示持久层
package com.example.demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.demo.entity.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Repository //@Mapper public interface UserMapper extends BaseMapper<User> { }
5.3 创建service 接口,需要继承IService
package com.example.demo.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.demo.entity.User; import java.util.List; public interface UserService extends IService<User> { /** * query all * @return */ List<User> queryAllUser(); }
5.4 实现service接口,需要继承 ServiceImpl
package com.example.demo.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> queryAllUser() { return userMapper.selectList(null); } }
5.5 创建controller
package com.example.demo.controller; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/user") public class UserInfoController { @Autowired private UserService userService; @RequestMapping("/queryAllUser") public List<User> queryAllUser(){ List<User> userList = userService.queryAllUser(); return userList; } }
6.测试类
测试类需要添加spring boot 的test依赖,其中已经依赖过了junit test 的依赖,不需要再进行单独添加。
package com.example.demo; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.example.demo.controller.UserInfoController; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import com.example.demo.service.UserService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @Slf4j @SpringBootTest class DemoApplicationTests { @Autowired private UserMapper userMapper; @Autowired private UserService userService; @Autowired private UserInfoController userInfoController; @Test void test() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name", "2"); User user = userMapper.selectOne(wrapper); log.info("userMapper.selectOne result is {}", JSON.toJSONString(user)); int count = userService.count(); System.out.println(count); log.info("userService.count() result is {}", count); List<User> userList = userInfoController.queryAllUser(); log.info("userInfoController.queryAllUser() result is {}", JSON.toJSONString(userList)); } }
如果使用以上测试时,出现测试类中注入的bean一直为空时,可使用下面的方式:
@RunWith(SpringRunner.class) @SpringBootTest(classes = GeneratorApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UserTest {
@Autowired
private UserService userService;
}
执行以上测试类截图:
7. 配置 mybatis plus 的分页
package com.example.demo.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisPlusConfig { // 分页插件 @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
通过 junit 进行调试
@Test void testPage() { Page<User> page = new Page<>(1, 5); IPage<User> paVo = userMapper.selectPage(page, null); log.info("------------------{}", JSON.toJSONString(paVo)); }
mybatis plus 分页之后的格式如下:
{ "current": 1, "orders": [], "pages": 1, "records": [{ "age": 3, "email": "4", "id": 1, "name": "2" }, { "age": 23, "email": "344", "id": 1352980081638248450, "name": "test" }, { "age": 23, "email": "344", "id": 1352980446211342337, "name": "test" }, { "age": 23, "email": "344", "id": 1352980660057944066, "name": "test" }], "searchCount": true, "size": 5, "total": 4 }
搭建框架过程中遇到的坑:
1. spring boot start启动的依赖是 spring-boot-starter-web ,不是 spring-boot-starter
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2. spring boot 默认解析的配置文件是 application.properties 文件,不是bootstrap.yaml , bootstrap.yaml 是spring cloud 中加载解析的配置文件格式