• springboot+mybatis-plus-join+mysql实现连表查询


    1. 简介

      Mybatis是目前比较主流的持久层框架,使用非常广泛。Mybatis-Plus是基于Mybatis增强工具包,越来越受到开发人员的喜爱。
      在使用Mybatis-Plus开发时,简单的crud可以直接使用其提供的接口或使用条件构造器。但对于关联表的查询,不论Mybatis还是Mybatis-Plus都需要自定义sql实现。
      Mybatis-Plus-Join基于Mybatis-Plus继续增强,提供了连表查询操作,简单易用。
      Mybatis-Plus-Join地址:https://gitee.com/best_handsome/mybatis-plus-join

    2. Mybatis-Plus相关博客

      SpringBoot + SpringSecurity + Mybatis-Plus + JWT实现分布式系统认证和授权SpringBoot + SpringSecurity + Mybatis-Plus + JWT + Redis 实现分布式系统认证和授权(刷新Token和Token黑名单)SpringBoot + Mybatis-Plus 实现多数据源简单示例SpringBoot + Layui +Mybatis-plus实现简单后台管理系统(内置安全过滤器)SpringBoot + Dubbo + Zookeeper +Mybatis-Plus + Mysql 搭建简单示例工程

    3. 初始化数据库

    1. CREATE DATABASE `mpj`;
    2. USE `mpj`;
    3. CREATE TABLE IF NOT EXISTS `t_user` (
    4. `id` int NOT NULL AUTO_INCREMENT COMMENT 'ID',
    5. `username` varchar(10) COMMENT '用户名称',
    6. `sex` char(1) COMMENT '性别',
    7. `phone` varchar(11) COMMENT '手机号',
    8. PRIMARY KEY (`id`)
    9. ) COMMENT = '用户信息表';
    10. INSERT INTO `t_user`(`id`, `username`, `sex`, `phone`) VALUES (1, '张三', '1', '13500000000');
    11. INSERT INTO `t_user`(`id`, `username`, `sex`, `phone`) VALUES (2, '李四', '0', '18311111111');
    12. CREATE TABLE IF NOT EXISTS `t_shipping_address` (
    13. `id` int NOT NULL AUTO_INCREMENT COMMENT 'ID',
    14. `user_id` int COMMENT '用户ID',
    15. `address` varchar(255) COMMENT '地址',
    16. `is_default` char(1) DEFAULT 'f' COMMENT '是否默认',
    17. PRIMARY KEY (`id`),
    18. INDEX `idx_user_id`(`user_id`) USING BTREE
    19. ) COMMENT = '收货地址表';
    20. INSERT INTO `t_shipping_address`(`id`, `user_id`, `address`, `is_default`) VALUES (1, 1, '陕西省西安市雁塔区', 't');
    21. INSERT INTO `t_shipping_address`(`id`, `user_id`, `address`, `is_default`) VALUES (2, 1, '陕西省西安市未央区', 'f');
    22. INSERT INTO `t_shipping_address`(`id`, `user_id`, `address`, `is_default`) VALUES (3, 2, '陕西省西安市莲湖区', 't');

    4. 示例代码

    • 创建项目
    • 修改pom.xml
    1. <project xmlns="http://maven.apache.org/POM/4.0.0"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0</modelVersion>
    5. <groupId>com.c3stones</groupId>
    6. <artifactId>mybatis-plus-join-demo</artifactId>
    7. <version>0.0.1-SNAPSHOT</version>
    8. <packaging>jar</packaging>
    9. <name>mybatis-plus-join-demo</name>
    10. <description>Mybatis-plus Join Demo</description>
    11. <parent>
    12. <groupId>org.springframework.boot</groupId>
    13. <artifactId>spring-boot-starter-parent</artifactId>
    14. <version>2.7.1</version>
    15. <relativePath />
    16. </parent>
    17. <dependencies>
    18. <dependency>
    19. <groupId>mysql</groupId>
    20. <artifactId>mysql-connector-java</artifactId>
    21. </dependency>
    22. <dependency>
    23. <groupId>com.github.yulichang</groupId>
    24. <artifactId>mybatis-plus-join</artifactId>
    25. <version>1.2.4</version>
    26. </dependency>
    27. <dependency>
    28. <groupId>com.baomidou</groupId>
    29. <artifactId>mybatis-plus-boot-starter</artifactId>
    30. <version>3.5.2</version>
    31. </dependency>
    32. <dependency>
    33. <groupId>org.projectlombok</groupId>
    34. <artifactId>lombok</artifactId>
    35. <optional>true</optional>
    36. </dependency>
    37. <dependency>
    38. <groupId>org.springframework.boot</groupId>
    39. <artifactId>spring-boot-starter-web</artifactId>
    40. </dependency>
    41. <dependency>
    42. <groupId>org.springframework.boot</groupId>
    43. <artifactId>spring-boot-starter-test</artifactId>
    44. <scope>test</scope>
    45. </dependency>
    46. <dependency>
    47. <groupId>junit</groupId>
    48. <artifactId>junit</artifactId>
    49. <scope>test</scope>
    50. </dependency>
    51. </dependencies>
    52. <build>
    53. <plugins>
    54. <plugin>
    55. <groupId>org.springframework.boot</groupId>
    56. <artifactId>spring-boot-maven-plugin</artifactId>
    57. </plugin>
    58. </plugins>
    59. </build>
    60. </project>
    • 添加配置文件application.yml
    1. spring:
    2. datasource:
    3. driver-class-name: com.mysql.cj.jdbc.Driver
    4. url: jdbc:mysql://127.0.0.1:3306/mpj?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
    5. username: root
    6. password: 123456
    7. # Mybatis-plus配置
    8. mybatis-plus:
    9. mapper-locations: classpath:mapper/*.xml
    10. global-config:
    11. db-config:
    12. id-type: AUTO
    13. configuration:
    14. # 打印sql
    15. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    • 配置Mybtis-Plus分页配置类
    1. /**
    2. * Mybatis-plus 配置类
    3. *
    4. * @author CL
    5. */
    6. @Configuration
    7. public class MybatisPlusConfig {
    8. @Bean
    9. public MybatisPlusInterceptor paginationInterceptor() {
    10. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    11. interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
    12. return interceptor;
    13. }
    14. }
    • 创建实体
    1. /**
    2. * 用户信息
    3. *
    4. * @author CL
    5. */
    6. @Data
    7. @EqualsAndHashCode(callSuper = false)
    8. @TableName(value = "t_user")
    9. public class User extends Model {
    10. private static final long serialVersionUID = 1L;
    11. @TableId
    12. private Integer id; // ID
    13. @TableField(condition = SqlCondition.LIKE)
    14. private String username; // 用户名称
    15. private String sex; // 性别
    16. private String phone; // 手机号
    17. }
    1. /**
    2. * 收货地址信息
    3. *
    4. * @author CL
    5. */
    6. @Data
    7. @EqualsAndHashCode(callSuper = false)
    8. @TableName(value = "t_shipping_address")
    9. public class ShippingAddress extends Model {
    10. private static final long serialVersionUID = 1L;
    11. @TableId
    12. private Integer id; // ID
    13. private Integer userId; // 用户ID
    14. private String address; // 地址
    15. private String isDefault; // 是否默认
    16. }
    • 创建Mapper
    1. /**
    2. * 用户 Mapper
    3. *
    4. * @author CL
    5. */
    6. @Mapper
    7. public interface UserMapper extends MPJBaseMapper<User> {
    8. }
    1. /**
    2. * 收货地址 Mapper
    3. *
    4. * @author CL
    5. */
    6. @Mapper
    7. public interface ShippingAddressMapper extends MPJBaseMapper<ShippingAddress> {
    8. }
    • 创建Service
        继承MPJBaseService类。
    1. /**
    2. * 用户 Service
    3. *
    4. * @author CL
    5. */
    6. public interface UserService extends MPJBaseService<User> {
    7. }
    • 创建Service实现
        继承MPJBaseServiceImpl类。
    1. /**
    2. * 用户 Service实现
    3. *
    4. * @author CL
    5. */
    6. @Service
    7. public class UserServiceImpl extends MPJBaseServiceImpl, User> implements UserService {
    8. }
    • 创建用户收货地址DTO
    1. /**
    2. * 用户收货地址 DTO
    3. *
    4. * @author CL
    5. */
    6. @Data
    7. @EqualsAndHashCode(callSuper = true)
    8. public class UserShippingAddressDto extends User {
    9. private static final long serialVersionUID = 1L;
    10. private String address; // 地址
    11. private String def; // 是否默认
    12. }
    • 创建Controller
    1. /**
    2. * 用户 Controller
    3. *
    4. * @author CL
    5. */
    6. @RestController
    7. @RequestMapping(value = "/user")
    8. public class UserController {
    9. @Autowired
    10. private UserService userService;
    11. /**
    12. * 查询用户列表数据
    13. *
    14. * @return
    15. */
    16. @RequestMapping(value = "/listData")
    17. public List<User> listData() {
    18. return userService.list(Wrappers.emptyWrapper());
    19. }
    20. /**
    21. * 查询用户分页数据
    22. *
    23. * @return
    24. */
    25. @RequestMapping(value = "/pageData")
    26. public IPage<User> pageData(long current, long size, User user) {
    27. return userService.page(new Page<>(current, size), Wrappers.query(user));
    28. }
    29. /**
    30. * 查询用户默认收货地址
    31. *
    32. * @return
    33. */
    34. @RequestMapping(value = "/default")
    35. public UserShippingAddressDto userDefaultShippingAddress(UserShippingAddressDto userShippingAddressDto) {
    36. return userService.selectJoinOne(UserShippingAddressDto.class, MPJWrappers.<User>lambdaJoin()
    37. .selectAll(User.class)
    38. .select(ShippingAddress::getAddress)
    39. .selectAs(ShippingAddress::getIsDefault, UserShippingAddressDto::getDef)
    40. .leftJoin(ShippingAddress.class, ShippingAddress::getUserId, User::getId)
    41. .eq(User::getId, userShippingAddressDto.getId())
    42. .eq(ShippingAddress::getIsDefault, "t")
    43. .last("limit 1"));
    44. }
    45. /**
    46. * 查询用户收货地址分页数据
    47. *
    48. * @return
    49. */
    50. @RequestMapping(value = "/pageAddressData")
    51. public IPage<UserShippingAddressDto> pageUserShippingAddressData(long current, long size, UserShippingAddressDto userShippingAddressDto) {
    52. // Mybatis-plus 对count进行了优化,因此需要关掉优化关联统计sql,详见:https://gitee.com/best_handsome/mybatis-plus-join/issues/I55FIU
    53. return userService.selectJoinListPage(new Page<>(current, size).setOptimizeCountSql(false), UserShippingAddressDto.class, MPJWrappers.<User>lambdaJoin()
    54. .selectAll(User.class)
    55. .select(ShippingAddress::getAddress)
    56. .selectAs(ShippingAddress::getIsDefault, UserShippingAddressDto::getDef)
    57. .leftJoin(ShippingAddress.class, ShippingAddress::getUserId, User::getId)
    58. .eq(Objects.nonNull(userShippingAddressDto.getId()), User::getId, userShippingAddressDto.getId())
    59. .like(StringUtils.isNotEmpty(userShippingAddressDto.getUsername()), User::getUsername, userShippingAddressDto.getUsername())
    60. .eq(StringUtils.isNotEmpty(userShippingAddressDto.getDef()), ShippingAddress::getIsDefault, userShippingAddressDto.getDef()));
    61. }
    62. /**
    63. * 统计用户收货地址数量
    64. *
    65. * @return
    66. */
    67. @RequestMapping(value = "/countAddress")
    68. public long countUserShippingAddress(UserShippingAddressDto userShippingAddressDto) {
    69. return userService.selectJoinCount(MPJWrappers.lambdaJoin()
    70. .select(ShippingAddress::getAddress)
    71. .leftJoin(ShippingAddress.class, ShippingAddress::getUserId, User::getId)
    72. .eq(User::getId, userShippingAddressDto.getId()));
    73. }
    74. }
    • 创建启动类
    1. /**
    2. * 启动类
    3. *
    4. * @author CL
    5. */
    6. @SpringBootApplication
    7. public class Application {
    8. public static void main(String[] args) {
    9. SpringApplication.run(Application.class, args);
    10. }
    11. }

    5. 单元测试

    • 使用Eclipse进行单元测试时,如果出现No tests found with test runner Junit5,原因是配置的JUnit版本和使用的JUnit不一致。右键Debug As -> Debug Configurations... -> Test runner,选择JUnit4即可。
    • /user/listData接口测试
    1. /**
    2. * UserController 单元测试
    3. *
    4. * @author CL
    5. */
    6. @RunWith(SpringRunner.class)
    7. @SpringBootTest
    8. public class UserControllerTest {
    9. @Autowired
    10. private UserController userController;
    11. private MockMvc mockMvc;
    12. @Before
    13. public void setup() {
    14. mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    15. }
    16. /**
    17. * /user/listData 接口测试
    18. */
    19. @Test
    20. public void listDataTest() throws Exception {
    21. mockMvc.perform(MockMvcRequestBuilders.get("/user/listData")).andExpect(status().isOk()) // 增加断言
    22. .andExpect(jsonPath("$[0].id").value(1)) // 增加断言
    23. .andExpect(jsonPath("$[1].id").value(2)) // 增加断言
    24. .andDo(print()) // 打印结果
    25. .andReturn();
    26. }
    27. }

      测试结果:

    1. MockHttpServletRequest:
    2. HTTP Method = GET
    3. Request URI = /user/listData
    4. Parameters = {}
    5. Headers = []
    6. Body = <no character encoding set>
    7. Session Attrs = {}
    8. Handler:
    9. Type = com.c3stones.controller.UserController
    10. Method = com.c3stones.controller.UserController#listData()
    11. Async:
    12. Async started = false
    13. Async result = null
    14. Resolved Exception:
    15. Type = null
    16. ModelAndView:
    17. View name = null
    18. View = null
    19. Model = null
    20. FlashMap:
    21. Attributes = null
    22. MockHttpServletResponse:
    23. Status = 200
    24. Error message = null
    25. Headers = [Content-Type:"application/json"]
    26. Content type = application/json
    27. Body = [{"id":1,"username":"张三","sex":"1","phone":"13500000000"},{"id":2,"username":"李四","sex":"0","phone":"18311111111"}]
    28. Forwarded URL = null
    29. Redirected URL = null
    30. Cookies = []
    • /user/pageData接口测试
    1. /**
    2. * UserController 单元测试
    3. *
    4. * @author CL
    5. */
    6. @RunWith(SpringRunner.class)
    7. @SpringBootTest
    8. public class UserControllerTest {
    9. @Autowired
    10. private UserController userController;
    11. private MockMvc mockMvc;
    12. @Before
    13. public void setup() {
    14. mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    15. }
    16. /**
    17. * /user/pageData 接口测试
    18. */
    19. @Test
    20. public void pageDataTest() throws Exception {
    21. mockMvc.perform(MockMvcRequestBuilders.get("/user/pageData").param("current", "1").param("size", "10"))
    22. .andExpectAll(status().isOk()).andExpect(jsonPath("$.total").value(2))
    23. .andDo(print()) // 打印结果
    24. .andReturn();
    25. mockMvc.perform(
    26. MockMvcRequestBuilders.get("/user/pageData").param("current", "1").param("size", "10").param("id", "1"))
    27. .andExpect(status().isOk()).andExpect(jsonPath("$.total").value(1))
    28. .andExpect(jsonPath("$.records[0].id").value(1))
    29. .andDo(print()) // 打印结果
    30. .andReturn();
    31. mockMvc.perform(MockMvcRequestBuilders.get("/user/pageData").param("current", "1").param("size", "10")
    32. .param("username", "张")).andExpect(status().isOk()).andExpect(jsonPath("$.total").value(1))
    33. .andExpect(jsonPath("$.records[0].username").value("张三"))
    34. .andDo(print()) // 打印结果
    35. .andReturn();
    36. }
    37. }

      测试结果:

    1. MockHttpServletRequest:
    2. HTTP Method = GET
    3. Request URI = /user/pageData
    4. Parameters = {current=[1], size=[10]}
    5. Headers = []
    6. Body = <no character encoding set>
    7. Session Attrs = {}
    8. Handler:
    9. Type = com.c3stones.controller.UserController
    10. Method = com.c3stones.controller.UserController#pageData(long, long, User)
    11. Async:
    12. Async started = false
    13. Async result = null
    14. Resolved Exception:
    15. Type = null
    16. ModelAndView:
    17. View name = null
    18. View = null
    19. Model = null
    20. FlashMap:
    21. Attributes = null
    22. MockHttpServletResponse:
    23. Status = 200
    24. Error message = null
    25. Headers = [Content-Type:"application/json"]
    26. Content type = application/json
    27. Body = {"records":[{"id":1,"username":"张三","sex":"1","phone":"13500000000"},{"id":2,"username":"李四","sex":"0","phone":"18311111111"}],"total":2,"size":10,"current":1,"orders":[],"optimizeCountSql":true,"searchCount":true,"countId":null,"maxLimit":null,"pages":1}
    28. Forwarded URL = null
    29. Redirected URL = null
    30. Cookies = []
    31. MockHttpServletRequest:
    32. HTTP Method = GET
    33. Request URI = /user/pageData
    34. Parameters = {current=[1], size=[10], id=[1]}
    35. Headers = []
    36. Body = <no character encoding set>
    37. Session Attrs = {}
    38. Handler:
    39. Type = com.c3stones.controller.UserController
    40. Method = com.c3stones.controller.UserController#pageData(long, long, User)
    41. Async:
    42. Async started = false
    43. Async result = null
    44. Resolved Exception:
    45. Type = null
    46. ModelAndView:
    47. View name = null
    48. View = null
    49. Model = null
    50. FlashMap:
    51. Attributes = null
    52. MockHttpServletResponse:
    53. Status = 200
    54. Error message = null
    55. Headers = [Content-Type:"application/json"]
    56. Content type = application/json
    57. Body = {"records":[{"id":1,"username":"张三","sex":"1","phone":"13500000000"}],"total":1,"size":10,"current":1,"orders":[],"optimizeCountSql":true,"searchCount":true,"countId":null,"maxLimit":null,"pages":1}
    58. Forwarded URL = null
    59. Redirected URL = null
    60. Cookies = []
    61. MockHttpServletRequest:
    62. HTTP Method = GET
    63. Request URI = /user/pageData
    64. Parameters = {current=[1], size=[10], username=[张]}
    65. Headers = []
    66. Body = <no character encoding set>
    67. Session Attrs = {}
    68. Handler:
    69. Type = com.c3stones.controller.UserController
    70. Method = com.c3stones.controller.UserController#pageData(long, long, User)
    71. Async:
    72. Async started = false
    73. Async result = null
    74. Resolved Exception:
    75. Type = null
    76. ModelAndView:
    77. View name = null
    78. View = null
    79. Model = null
    80. FlashMap:
    81. Attributes = null
    82. MockHttpServletResponse:
    83. Status = 200
    84. Error message = null
    85. Headers = [Content-Type:"application/json"]
    86. Content type = application/json
    87. Body = {"records":[{"id":1,"username":"张三","sex":"1","phone":"13500000000"}],"total":1,"size":10,"current":1,"orders":[],"optimizeCountSql":true,"searchCount":true,"countId":null,"maxLimit":null,"pages":1}
    88. Forwarded URL = null
    89. Redirected URL = null
    90. Cookies = []
    • /user/default接口测试
    1. /**
    2. * UserController 单元测试
    3. *
    4. * @author CL
    5. */
    6. @RunWith(SpringRunner.class)
    7. @SpringBootTest
    8. public class UserControllerTest {
    9. @Autowired
    10. private UserController userController;
    11. private MockMvc mockMvc;
    12. @Before
    13. public void setup() {
    14. mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    15. }
    16. /**
    17. * /user/default 接口测试
    18. */
    19. @Test
    20. public void userDefaultShippingAddressTest() throws Exception {
    21. mockMvc.perform(MockMvcRequestBuilders.get("/user/default").param("id", "1")).andExpect(status().isOk())
    22. .andExpect(jsonPath("$.def").value("t"))
    23. .andDo(print()) // 打印结果
    24. .andReturn();
    25. mockMvc.perform(MockMvcRequestBuilders.get("/user/default").param("id", "999"))
    26. .andExpect(status().is2xxSuccessful())
    27. .andDo(print()) // 打印结果
    28. .andReturn();
    29. }
    30. }

      测试结果:

    1. MockHttpServletRequest:
    2. HTTP Method = GET
    3. Request URI = /user/default
    4. Parameters = {id=[1]}
    5. Headers = []
    6. Body = <no character encoding set>
    7. Session Attrs = {}
    8. Handler:
    9. Type = com.c3stones.controller.UserController
    10. Method = com.c3stones.controller.UserController#userDefaultShippingAddress(UserShippingAddressDto)
    11. Async:
    12. Async started = false
    13. Async result = null
    14. Resolved Exception:
    15. Type = null
    16. ModelAndView:
    17. View name = null
    18. View = null
    19. Model = null
    20. FlashMap:
    21. Attributes = null
    22. MockHttpServletResponse:
    23. Status = 200
    24. Error message = null
    25. Headers = [Content-Type:"application/json"]
    26. Content type = application/json
    27. Body = {"id":1,"username":"张三","sex":"1","phone":"13500000000","address":"陕西省西安市雁塔区","def":"t"}
    28. Forwarded URL = null
    29. Redirected URL = null
    30. Cookies = []
    31. MockHttpServletRequest:
    32. HTTP Method = GET
    33. Request URI = /user/default
    34. Parameters = {id=[999]}
    35. Headers = []
    36. Body = <no character encoding set>
    37. Session Attrs = {}
    38. Handler:
    39. Type = com.c3stones.controller.UserController
    40. Method = com.c3stones.controller.UserController#userDefaultShippingAddress(UserShippingAddressDto)
    41. Async:
    42. Async started = false
    43. Async result = null
    44. Resolved Exception:
    45. Type = null
    46. ModelAndView:
    47. View name = null
    48. View = null
    49. Model = null
    50. FlashMap:
    51. Attributes = null
    52. MockHttpServletResponse:
    53. Status = 200
    54. Error message = null
    55. Headers = []
    56. Content type = null
    57. Body =
    58. Forwarded URL = null
    59. Redirected URL = null
    60. Cookies = []
    • /user/pageAddressData接口测试
    1. /**
    2. * UserController 单元测试
    3. *
    4. * @author CL
    5. */
    6. @RunWith(SpringRunner.class)
    7. @SpringBootTest
    8. public class UserControllerTest {
    9. @Autowired
    10. private UserController userController;
    11. private MockMvc mockMvc;
    12. @Before
    13. public void setup() {
    14. mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    15. }
    16. /**
    17. * /user/pageAddressData 接口测试
    18. */
    19. @Test
    20. public void pageUserShippingAddressDataTest() throws Exception {
    21. mockMvc.perform(MockMvcRequestBuilders.get("/user/pageAddressData").param("current", "1").param("size", "10"))
    22. .andExpect(status().isOk()).andExpect(jsonPath("$.total").value(3))
    23. .andDo(print()) // 打印结果
    24. .andReturn();
    25. }
    26. }

      测试结果:

    1. MockHttpServletRequest:
    2. HTTP Method = GET
    3. Request URI = /user/pageAddressData
    4. Parameters = {current=[1], size=[10]}
    5. Headers = []
    6. Body = <no character encoding set>
    7. Session Attrs = {}
    8. Handler:
    9. Type = com.c3stones.controller.UserController
    10. Method = com.c3stones.controller.UserController#pageUserShippingAddressData(long, long, UserShippingAddressDto)
    11. Async:
    12. Async started = false
    13. Async result = null
    14. Resolved Exception:
    15. Type = null
    16. ModelAndView:
    17. View name = null
    18. View = null
    19. Model = null
    20. FlashMap:
    21. Attributes = null
    22. MockHttpServletResponse:
    23. Status = 200
    24. Error message = null
    25. Headers = [Content-Type:"application/json"]
    26. Content type = application/json
    27. Body = {"records":[{"id":1,"username":"张三","sex":"1","phone":"13500000000","address":"陕西省西安市未央区","def":"f"},{"id":1,"username":"张三","sex":"1","phone":"13500000000","address":"陕西省西安市雁塔区","def":"t"},{"id":2,"username":"李四","sex":"0","phone":"18311111111","address":"陕西省西安市莲湖区","def":"t"}],"total":3,"size":10,"current":1,"orders":[],"optimizeCountSql":false,"searchCount":true,"countId":null,"maxLimit":null,"pages":1}
    28. Forwarded URL = null
    29. Redirected URL = null
    30. Cookies = []
    • /user/countAddress接口测试
    1. /**
    2. * UserController 单元测试
    3. *
    4. * @author CL
    5. */
    6. @RunWith(SpringRunner.class)
    7. @SpringBootTest
    8. public class UserControllerTest {
    9. @Autowired
    10. private UserController userController;
    11. private MockMvc mockMvc;
    12. @Before
    13. public void setup() {
    14. mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    15. }
    16. /**
    17. * /user/countAddress 接口测试
    18. */
    19. @Test
    20. public void countUserShippingAddressTest() throws Exception {
    21. mockMvc.perform(MockMvcRequestBuilders.get("/user/countAddress").param("id", "1")).andExpect(status().isOk())
    22. .andExpect(content().string("2"))
    23. .andDo(print()) // 打印结果
    24. .andReturn();
    25. mockMvc.perform(MockMvcRequestBuilders.get("/user/countAddress").param("id", "2")).andExpect(status().isOk())
    26. .andExpect(content().string("1"))
    27. .andDo(print()) // 打印结果
    28. .andReturn();
    29. }
    30. }

      测试结果:

    1. MockHttpServletRequest:
    2. HTTP Method = GET
    3. Request URI = /user/countAddress
    4. Parameters = {id=[1]}
    5. Headers = []
    6. Body = <no character encoding set>
    7. Session Attrs = {}
    8. Handler:
    9. Type = com.c3stones.controller.UserController
    10. Method = com.c3stones.controller.UserController#countUserShippingAddress(UserShippingAddressDto)
    11. Async:
    12. Async started = false
    13. Async result = null
    14. Resolved Exception:
    15. Type = null
    16. ModelAndView:
    17. View name = null
    18. View = null
    19. Model = null
    20. FlashMap:
    21. Attributes = null
    22. MockHttpServletResponse:
    23. Status = 200
    24. Error message = null
    25. Headers = [Content-Type:"application/json"]
    26. Content type = application/json
    27. Body = 2
    28. Forwarded URL = null
    29. Redirected URL = null
    30. Cookies = []
    31. MockHttpServletRequest:
    32. HTTP Method = GET
    33. Request URI = /user/countAddress
    34. Parameters = {id=[2]}
    35. Headers = []
    36. Body = <no character encoding set>
    37. Session Attrs = {}
    38. Handler:
    39. Type = com.c3stones.controller.UserController
    40. Method = com.c3stones.controller.UserController#countUserShippingAddress(UserShippingAddressDto)
    41. Async:
    42. Async started = false
    43. Async result = null
    44. Resolved Exception:
    45. Type = null
    46. ModelAndView:
    47. View name = null
    48. View = null
    49. Model = null
    50. FlashMap:
    51. Attributes = null
    52. MockHttpServletResponse:
    53. Status = 200
    54. Error message = null
    55. Headers = [Content-Type:"application/json"]
    56. Content type = application/json
    57. Body = 1
    58. Forwarded URL = null
    59. Redirected URL = null
    60. Cookies = []

    6. 项目地址

      mybatis-plus-join-demo

  • 相关阅读:
    C# 压缩图片
    文本分析总结
    FPGA千兆网 UDP 网络视频传输,基于88E1518 PHY实现,提供工程和QT上位机源码加技术支持
    java计算机毕业设计疫情下图书馆管理系统源程序+mysql+系统+lw文档+远程调试
    【idea】解决idea 执行maven build总下载 Downloading maven-metadata.xml文件
    【个人博客系统网站】注册与登录 · 加盐加密验密算法 · 上传头像
    MySQL数据库 #2
    什么是业务流程图(TFD),数据字典(DD),数据流程图(DFD)
    哈希冲突概念及其四种解决方案
    java+ssm+vue基本微信小程序的高速公路服务区充电桩在线预订系统 uniapp小程序
  • 原文地址:https://blog.csdn.net/qq_48008521/article/details/126496425