SpringCloud+SpringBoot 项目搭建 (三) MyBatis-Push

本篇文章接上一篇:SpringCloud+SpringBoot 项目搭建 (二) Redis

MyBatis-Plus集成

MyBatis-Plus简介

MyBatis-Plus 是一个 Mybatis 增强版工具,在 MyBatis 上扩充了其他功能没有改变其基本功能,为了简化开发提交效率而存在。

官网文档地址:
  https://mp.baomidou.com/guide/

MyBatis-Plus 特性:
  https://mp.baomidou.com/guide/#%E7%89%B9%E6%80%A7

引入MyBatis-Puls

		 	<properties>
 				<mybaits-plus.version>3.4.0</mybaits-plus.version>
 			</properties>
			<!--mybatis-plus-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybaits-plus.version}</version>
            </dependency>
            <!--mysql依赖-->
            <dependency>
	            <groupId>mysql</groupId>
	            <artifactId>mysql-connector-java</artifactId>
	        </dependency>
	         <!--model操作-->
  			<dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.14</version>
            </dependency>

配置properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterCode=utf8

创建model和mapper

/**model*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("user_info")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
    private String phone;
}
/**mapper*/
public interface UserMapper extends BaseMapper<User> {
}

在MyBatis-Plus中BaseMapper是封装好的一个类,里面有常用的crud的方法。这里直接使用。
在启动中添加扫描注解
在这里插入图片描述

@MapperScan("com.dongyue.usercenter.mapper")
@SpringBootApplication
@EnableEurekaClient
public class UserCenterApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserCenterApplication.class, args);
    }
}

添加测试方法测试是否能成功调用数据库

@SpringBootTest
class UserCenterApplicationTests {
    @Autowired
    private UserMapper userMapper;
    @Test
    void testSelect(){
        System.out.println(("**************** test selectById start ****************"));
        User user = userMapper.selectById(1);
        System.out.println(user);
        System.out.println(("**************** test selectById end ****************"));
    }
}

在这里插入图片描述
通过以上操作,就完成了MyBatis-Plus的搭建,如需更多操作请查看官方文档。

MyBatis-Plus代码生成器

简介官方说明

MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。与 mybatis 中的 mybatis-generator-core 类似。

引入maven

 			<!--mybatis代码生成器-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>${mybaits-plus.version}</version>
            </dependency>
            <!--代码生成器需要使用的模板-->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version>2.3</version>
            </dependency>

生成器全代码

public class UserGenerator {
    //项目路径
    private static String canonicalPath = Class.class.getClass().getResource("/").getPath();

    //基本包名
    private static String basePackage = "com.dongyue.usercenter";
    //作者
    private static String authorName = "rdy";
    //要生成的表名
    private static String[] tables = null;
    //table前缀
    private static String prefix = "";
    //数据库类型
    private static DbType dbType = DbType.MYSQL;
    //数据库配置四要素
    private static String driverName = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
    private static String username = "root";
    private static String password = "root";
	//key为子包名称   list为表
    private static Map<String,List<String>> map  = new HashMap<>();

    static{
        List<String> list = new ArrayList<>();
        list.add("user");
        map.put("user",list);
        tables = list.toArray(new String[1]);
    }

    public static void main(String[] args) throws IOException {

        Set<Map.Entry<String, List<String>>> entries = map.entrySet();
        for (Map.Entry<String, List<String>> entry : entries) {
            String src = entry.getKey();
            List<String> list = entry.getValue();

            AutoGenerator gen = new AutoGenerator();

            /**
             * 获取项目路径
             */
//            try {
                canonicalPath = new File("").getCanonicalPath();
                canonicalPath = canonicalPath + "\\provider\\usercenter";
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
            /**
             * 数据库配置
             */
            gen.setDataSource(new DataSourceConfig()
                    .setDbType(dbType)
                    .setDriverName(driverName)
                    .setUrl(url)
                    .setUsername(username)
                    .setPassword(password)
                    .setTypeConvert(new MySqlTypeConvert() {
                    }));

            /**
             * 全局配置
             */
            gen.setGlobalConfig(new GlobalConfig()
                    .setOutputDir( canonicalPath + "/src/main/java")//输出目录
                    .setFileOverride(false)// 是否覆盖文件
                    .setActiveRecord(true)// 开启 activeRecord 模式
                    .setEnableCache(false)// XML 二级缓存
                    .setBaseResultMap(true)// XML ResultMap
                    .setBaseColumnList(true)// XML columList
                    .setOpen(false)//生成后打开文件夹
                    .setAuthor(authorName)
                    // 自定义文件命名,注意 %s 会自动填充表实体属性!
                    .setMapperName("%sMapper")
                    .setXmlName("%sMapper")
//                    .setServiceName("%sService")
//                    .setServiceImplName("%sServiceImpl")
//                    .setControllerName("%sController")

            );

            /**
             * 策略配置
             */
            gen.setStrategy(new StrategyConfig()
                            // .setCapitalMode(true)// 全局大写命名
                            //.setDbColumnUnderline(true)//全局下划线命名
                            .setTablePrefix(new String[]{prefix})// 此处可以修改为您的表前缀
                            .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
                            .setInclude(list.toArray(new String[0])) // 需要生成的表
                            .setRestControllerStyle(false)
                            //.setExclude(new String[]{"test"}) // 排除生成的表
                            // 自定义实体父类
                            // .setSuperEntityClass("com.baomidou.demo.TestEntity")
                            // 自定义实体,公共字段
                            //.setSuperEntityColumns(new String[]{"test_id"})
                            //.setTableFillList(tableFillList)
                            // 自定义 mapper 父类 默认BaseMapper
                            //.setSuperMapperClass("com.baomidou.mybatisplus.mapper.BaseMapper")
                            // 自定义 service 父类 默认IService
                            // .setSuperServiceClass("com.baomidou.demo.TestService")
                            // 自定义 service 实现类父类 默认ServiceImpl
                            // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
                            // 自定义 controller 父类
                            //.setSuperControllerClass("com.kichun."+packageName+".controller.AbstractController")
                            // 【实体】是否生成字段常量(默认 false)
                            // public static final String ID = "test_id";
                            // .setEntityColumnConstant(true)
                            // 【实体】是否为构建者模型(默认 false)
                            // public User setName(String name) {this.name = name; return this;}
                            // .setEntityBuilderModel(true)
                            // 【实体】是否为lombok模型(默认 false)<a href="https://projectlombok.org/">document</a>
                            .setEntityLombokModel(true)
                    // Boolean类型字段是否移除is前缀处理
                    // .setEntityBooleanColumnRemoveIsPrefix(true)
                    // .setRestControllerStyle(true)
                    // .setControllerMappingHyphenStyle(true)
            );

            /**
             * 包配置
             */
            gen.setPackageInfo(new PackageConfig()
                    //.setModuleName("User")
                    .setParent(basePackage)// 自定义包路径
//                    .setController("controller"+"."+src)// 这里是控制器包名,默认 web
                    .setEntity("domain"+"."+src) // 设置Entity包名,默认entity
                    .setMapper("mapper"+"."+src) // 设置Mapper包名,默认mapper
//                    .setService("service"+"."+src) // 设置Service包名,默认service
//                    .setServiceImpl("service.impl"+"."+src) // 设置Service Impl包名,默认service.impl
                    .setXml("mapper"+"."+src) // 设置Mapper XML包名,默认mapper.xml
            );

            /**
             * 注入自定义配置
             */
            // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
            InjectionConfig abc = new InjectionConfig() {
                @Override
                public void initMap() {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                    this.setMap(map);
                }
            };

            abc.setFileCreate(new IFileCreate() {
                @Override
                public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                    // 判断自定义文件夹是否需要创建,这里调用默认的方法
                    if(FileType.CONTROLLER.equals(fileType)||FileType.SERVICE.equals(fileType)||FileType.SERVICE_IMPL.equals(fileType)){
                        return false;
                    }
                    checkDir(filePath);
                    //对于已存在的文件,只需重复生成 entity 和 mapper.xml
                    File file = new File(filePath);
                    boolean exist = file.exists();
                    if(exist){
                        if (FileType.ENTITY==fileType){
                            return true;
                        }else {
                            return false;
                        }
                    }
                    //不存在的文件都需要创建
                    return  true;
                }
            });
            //自定义文件输出位置(非必须)
            List<FileOutConfig> fileOutList = new ArrayList<FileOutConfig>();
            fileOutList.add(new FileOutConfig("/templates/mapper.xml.vm") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    String path = canonicalPath + "/src/main/resources/com/dongyue/usercenter/mapper/" + src;
                    File file = new File(path);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    return path+"/" + tableInfo.getEntityName() + "Mapper.xml";
                }
            });
            abc.setFileOutConfigList(fileOutList);
            gen.setCfg(abc);

            /**
             * 指定模板引擎 默认是VelocityTemplateEngine ,需要引入相关引擎依赖
             */
            gen.setTemplateEngine(new VelocityTemplateEngine());

            /**
             * 模板配置
             */
            gen.setTemplate(new TemplateConfig().setXml(null)
                    // 关闭默认 xml 生成,调整生成 至 根目录
//					getMyTemplateConfig(basePackage)
                    // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
                    // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
                    // .setController("...");
                    // .setEntity("...");
                    // .setMapper("...");
                    // .setXml("...");
                    // .setService("...");
                    // .setServiceImpl("...");
            );
            // 执行生成
            gen.execute();
        }
    }
    private static void initVm(TemplateConfig tc){
        tc.setMapper("/templates/vm/myMapper.java");
    }
    /**
     * 自定义模板配置
     */
    private static TemplateConfig getMyTemplateConfig(String basePackage){
        TemplateConfig tc = new TemplateConfig();
        initVm(tc);
//		Path entity = Paths.get(canonicalPath, String.join("/", basePackage.split("\\.")), "entity");
//		File file = new File(entity.toString());
//		String[] list = file.list();
//		if(list!=null&&list.length>0){
//			tc.setController(null);
//			tc.setXml(null);
//			tc.setMapper(null);
//			tc.setService(null);
//			tc.setServiceImpl(null);
//		}
        return tc;
    }
}

下一篇:SpringCloud+SpringBoot 项目搭建 (四) RockerMq

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值