集成Mybatis-Plus

集成Mybatis-Plus

引入依赖

 <!-- mybatis-plus依赖 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
</dependency>
 <!-- alibaba的druid数据库连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.20</version>
</dependency>
 <!-- log4j2日志 -->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-log4j2</artifactId>
     <version>2.4.3</version>
</dependency>
<dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>8.0.23</version>
     <scope>runtime</scope>
</dependency>

配置文件

# server基础配置
server:
  port: 8096 
  servlet:
    context-path: /mybatis #上下文

spring:
  application:
    name: mybatis-plus #项目名字
  datasource: # 数据源
    name: xlt-ds
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    druid:  #druid相关配置
      filters: stat #监控统计拦截的filters
      initial-size: 1  #配置初始化大小/最小/最大
      min-idle: 1
      max-active: 20
      max-wait: 60000 #获取连接等待超时时间
      time-between-eviction-runs-millis: 60000  #间隔多久进行一次检测,检测需要关闭的空闲连接
      min-evictable-idle-time-millis: 300000  #一个连接在池中最小生存的时间
      validation-query: SELECT 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: false #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
      max-pool-prepared-statement-per-connection-size: 20

# mybatis配置
mybatis:
  config-location: classpath:config/mybatis-config.xml
  mapper-locations: classpath:com/xxx/xlt/mybatis/mapper/*.xml
  type-aliases-package: com.xxx.xlt.mybatis.model.po
# mybatis-plus配置
mybatis-plus:
  global-config:
    db-config:
      id-type: auto
  configuration: #配置日志输出
    log-impl: org.apache.ibatis.logging.log4j2.Log4j2Impl
    
# log4j2配置
logging:
  config: classpath:log/log4j2.xml
  level:
    com.xxx.xlt.mybatis.mapper: debug # 输出mybatis-plus的SQL

启动文件

启动类中增加MapperScan可以自动扫描对用包下的mapper

@SpringBootApplication
@MapperScan("com.xxx.xlt.mybatis.mapper")
public class MyBatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyBatisApplication.class,args);
    }
}

代码相关

1、使用mybatis需要继承BaseMapper

public interface UserMapper extends BaseMapper<UserPo> {
}

2、UserPo跟数据库表字段映射

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName("user_t")
public class UserPo {
    @TableId("id")
    private Long id;

    @TableField("number")
    private String number;

    @TableField("name")
    private String name;

    @TableField("position")
    private String position;
}

3、定义CRUD接口

public interface IUserService {
    DataResponse<List<UserVo>> queryUserList(UserVo userVo);

    BasicResponse addUser(UserVo userVo);

    BasicResponse updateUser(UserVo userVo);

    BasicResponse deleteUser(Long userId);
}

4、实现类

@Service
@Slf4j
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public DataResponse<List<UserVo>> queryUserList(UserVo userVo) {
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(userVo.getId())) {
            queryWrapper.eq("id", userVo.getId());
        }
        if (StringUtils.isNotEmpty(userVo.getName())) {
            queryWrapper.like("name", userVo.getName()); // 全模糊
        }
        if (StringUtils.isNotEmpty(userVo.getNumber())) {
            queryWrapper.likeRight("number", userVo.getNumber()); // 后模糊
        }
        if (StringUtils.isNotEmpty(userVo.getPosition())) {
            queryWrapper.likeLeft("position", userVo.getPosition()); // 前模糊
        }
        List<UserPo> userPos = userMapper.selectList(queryWrapper);
        List<UserVo> userVos = new ArrayList<>();
        try {
            for (UserPo userPo:userPos) {
                UserVo tmp = new UserVo();
                BeanUtils.copyProperties(tmp, userPo);
                userVos.add(tmp);
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error("convert error:", e);
        }
        return new DataResponse<>(userVos);
    }

    @Override
    public BasicResponse addUser(UserVo userVo) {
        UserPo userPo = new UserPo();
        try {
            BeanUtils.copyProperties(userPo,userVo);
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error("convert vo to po error:",e);
        }
        userMapper.insert(userPo);
        return new BasicResponse();
    }

    @Override
    public BasicResponse updateUser(UserVo userVo) {
        UserPo userPo = new UserPo();
        try {
            BeanUtils.copyProperties(userPo,userVo);
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error("convert vo to po error:",e);
        }
        userMapper.updateById(userPo);
        return new BasicResponse();
    }

    @Override
    public BasicResponse deleteUser(Long userId) {
        userMapper.deleteById(userId);
        return new BasicResponse();
    }
}

5、Controller

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json")
    BasicResponse addUser(@RequestBody UserVo userVo) {
        return userService.addUser(userVo);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json")
    BasicResponse deleteUser(@PathVariable("id") Long id) {
        return userService.deleteUser(id);
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT, produces = "application/json")
    BasicResponse updateUser(@RequestBody UserVo userVo) {
        return userService.updateUser(userVo);
    }

    @RequestMapping(value = "/query/list", method = RequestMethod.GET, produces = "application/json")
    BasicResponse queryUserList(@Param("userVo") UserVo userVo) {
        return userService.queryUserList(userVo);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值