SpringBoot使用MybatisGenerator操作数据

为了增强Mybatis的功能性和易用性,有两种比较常用的方案

Mybatis Genenrator
Mybatis Plus

一、整合Mybatis

第一步:引入maven依赖包,包括mybatis相关依赖包和mysql驱动包。

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

第二步:保证application.yml里面有数据库连接的配置。并配置mybatis的xml文件存放位置,下文配置的xml文件目录位置是resources/generator。

spring:
  datasource:
    url: jdbc:mysql://192.168.161.3:3306/testdb?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: test
    password: 4rfv$RFV
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
    mapper-locations: classpath:generator/*.xml
logging:
    level:
      com.zimug.bootlaunch: debug

mybatis.mapper-locations表示去哪里扫描xml文件

第三步:配置Mybatis的Mapper类文件的包扫描路径

@SpringBootApplication
@MapperScan(basePackages = {"com.zimug.boot.launch.generator"})
public class BootLaunchApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootLaunchApplication.class, args);
    }

}

二、安装Mybatis generator插件

Mybatis Generator可以自动的帮助我们根据数据库表结构生成持久层的代码,能很大层度上帮助我们提高开发效率。Mybatis generator的使用方法有很多种,比如:

XML配置文件实现Mybatis Generator代码生成配置
编码实现Mybatis Generator代码生成配置
通过IDEA插件实现Mybatis Generator代码生成配置
其中最简单易用的就是Mybatis Generator的IDEA插件来生成代码,直观、简单、易用。其实Mybatis Generator插件有很多,最常使用的一个:better-mybatis-generator(免费开源好用)

前往better-mybatis-generator具体操作步骤
生成如下:



主要生成了实体类和dao层的持久化代码

添加Service层

package com.dj.lunch.service;

import com.dj.lunch.model.TtUser;

public  interface TtUserResService {
    TtUser selectById(Integer id);
}
@Service
public class TtUserDaoService implements TtUserResService {

    @Autowired
    TtUserDao ttUserDao;


    @Override
    public TtUser selectById(Integer id) {
        TtUser u = ttUserDao.selectByPrimaryKey(id);
        return u;
    }

添加controller类进行数据库操作


@RestController
public class UserDaojdbcTest {

    @Autowired
    private TtUserResService ttUserResService;
    @RequestMapping(method = RequestMethod.GET,value = "select/{id}")
    public TtUser findone(@PathVariable("id") int id){
        TtUser tuser =  ttUserResService.selectById(id);
        return tuser;
    }
}

操作结果:

http://localhost:8079/select/6

{
    "id": 6,
    "userName": "zimug",
    "birthday": "2021-01-27T11:59:26.000+00:00",
    "address": "ok",
    "sex": "南"
}

源码地址

参考链接: https://www.kancloud.cn/hanxt/springboot2/1794118
https://blog.csdn.net/zhenghuishengq/article/details/109510128

posted @ 2021-01-28 18:45  离人怎挽_wdj  阅读(179)  评论(0编辑  收藏  举报