Springboot使用Mybatisplus:BaseMapper与IService

您所在的位置:网站首页 的pageQueryParam分页是哪个依赖 Springboot使用Mybatisplus:BaseMapper与IService

Springboot使用Mybatisplus:BaseMapper与IService

2024-06-10 05:21| 来源: 网络整理| 查看: 265

(一)仅使用BaseMapper中提供方法 1.导入依赖:pom.xml org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test com.baomidou mybatis-plus-boot-starter 3.4.0 mysql mysql-connector-java org.projectlombok lombok org.springframework.boot spring-boot-starter-web 2.数据准备:编写数据库及对应的实体类,并连接数据库

在这里插入图片描述

import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }

连接数据库application.yml

spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver 3.编写Mapper接口

接口继承BaseMapper,简易测试:【仅使用BaseMapper中方法可不编写Mapper.xml文件】

mapper接口:

@Repository//@Mapper更专业 public interface UserMapper extends BaseMapper { }

简易测试:

@SpringBootTest public class SampleTest { @Autowired private UserMapper userMapper; @Test public void testSelect() { System.out.println(("----- selectAll method test ------")); List userList = userMapper.selectList(null); assertEquals(5, userList.size()); userList.forEach(System.out::println); } @Test public void test02(){ QueryWrapper queryWrapper=new QueryWrapper(); queryWrapper.ge("age",20) .le("id",4); List users = userMapper.selectList(queryWrapper); for (User user : users) { System.out.println(user); } } (二)自定义 非BaseMapper中方法操作数据库

在(一)的完全基础上:

1.在Mapper接口声明自定义的方法: @Repository public interface UserMapper extends BaseMapper { User selectUserById(Integer id); } 2.编写对应的Mapper.xml文件 DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> select * from user where id=#{id} 3.在application.yml的mybatisplus相关配置中声明Mapper.xml文件所在位置 spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: mapper-locations: classpath:/mapper/*Mapper.xml 4.简易测试 @Autowired private UserMapper userMapper; @Test public void test03(){ User user = userMapper.selectUserById(3); System.out.println(user); } (三)使用IService

在一的基础上:

1.编写Service接口继承IService public interface UserSerivce extends IService { } 2.编写实现类UserServiceImpl

继承ServiceImpl,并实现UserService

@Service public class UserServiceImpl extends ServiceImpl implements UserSerivce { } 3.编写controller层,进行测试 @RestController public class TestController { @Autowired UserServiceImpl userServiceImpl; @RequestMapping("/select") public List select(){ return userServiceImpl.list(); } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3