SpringBoot下使用MyBatis

网友投稿 227 2022-11-17


SpringBoot下使用MyBatis

1.官方地址:

http://mybatis.plus/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B

2.数据库结构:

3.依赖导入

mysql

mysql-connector-java

runtime

5.1.39

com.baomidou

mybatis-plus-boot-starter

3.4.0

com.baomidou

mybatis-plus-generator

3.4.0

http://

org.freemarker

freemarker

2.3.30

org.projectlombok

lombok

true

配置freemarker是因为myBatis中默认的引擎是freemarker,支持自定义引擎

3.目录结构

4.官方生成器类

CodeGenerator

public class CodeGenerator {

/**

*

* 读取控制台内容

*

*/

public static String scanner(String tip) {

Scanner scanner = new Scanner(System.in);

StringBuilder help = new StringBuilder();

help.append("请输入" + tip + ":");

System.out.println(help.toString());

if (scanner.hasNext()) {

String ipt = scanner.next();

if (StringUtils.isNotBlank(ipt)) {

return ipt;

}

}

throw new MybatisPlusException("请输入正确的" + tip + "!");

}

public static void main(String[] args) {

// 代码生成器

AutoGenerator mpg = new AutoGenerator();

// 全局配置

GlobalConfig gc = new GlobalConfig();

String projectPath = System.getProperty("user.dir");

/**

* 这里需要设定一下保存的地址是本项目下的/src/main/java

*/

gc.setOutputDir(projectPath + "/maven1018/src/main/java");

gc.setAuthor("XYD");

gc.setOpen(false);

// gc.setSwagger2(true); 实体属性 Swagger2 注解

mpg.setGlobalConfig(gc);

// 数据源配置

/**

* 设置数据库名称和数据库账户密码

*/

DataSourceConfig dsc = new DataSourceConfig();

dsc.setUrl("jdbc:mysql://localhost:3306/temporary?useUnicode=true&useSSL=false&characterEncoding=utf8");

// dsc.setSchemaName("public");

dsc.setDriverName("com.mysql.jdbc.Driver");

dsc.setUsername("root");

dsc.setPassword("12345");

mpg.setDataSource(dsc);

// 包配置

/**

* 设置生成文件保存地址,模块名为命令窗口输入的模块名

*/

PackageConfig pc = new PackageConfig();

pc.setModuleName(scanner("模块名"));

pc.setParent("com.baomidou.ant");

mpg.setPackageInfo(pc);

// 自定义配置

InjectionConfig cfg = new InjectionConfig() {

@Override

public void initMap() {

// to do nothing

}

};

// 如果模板引擎是 freemarker

// String templatePath = "/templates/mapper.xml.ftl";

// 如果模板引擎是 velocity

// String templatePath = "/templates/mapper.xml.vm";

/**

* 这里定义的是生成xml文档的输出配置,存放在resource下

*/

// 自定义输出配置

// List focList = new ArrayList<>();

// 自定义配置会被优先输出

// focList.add(new FileOutConfig(templatePath) {

// @Override

// public String outputFile(TableInfo tableInfo) {

// // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!

// return projectPath + "/maven1018/src/main/resources/mapper/" + pc.getModuleName()

// + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;

// }

// });

/*

cfg.setFileCreate(new IFileCreate() {

@Override

public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {

// 判断自定义文件夹是否需要创建

checkDir("调用默认方法创建的目录,自定义目录用");

if (fileType == FileType.MAPPER) {

// 已经生成 mapper 文件判断存在,不想重新生成返回 false

return !new File(filePath).exists();

}

// 允许生成模板文件

return true;

}

});

*/

// cfg.setFileOutConfigList(focList);

// mpg.setCfg(cfg);

// 配置模板

TemplateConfig templateConfig = new TemplateConfig();

// 配置自定义输出模板

//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别

// templateConfig.setEntity("templates/entity2.java");

// templateConfig.setService();

// templateConfig.setController();

templateConfig.setXml(null);

mpg.setTemplate(templateConfig);

// 策略配置

StrategyConfig strategy = new StrategyConfig();

strategy.setNaming(NamingStrategy.underline_to_camel);

strategy.setColumnNaming(NamingStrategy.underline_to_camel);

// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");

strategy.setEntityLombokModel(true);

strategy.setRestControllerStyle(true);

// 公共父类

// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");

// 写于父类中的公共字段

// strategy.setSuperEntityColumns("id"); //注释这行否则生成的实体类中没有Id变量

strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));

strategy.setControllerMappingHyphenStyle(true);

strategy.setTablePrefix(pc.getModuleName() + "_");

mpg.setStrategy(strategy);

mpg.setTemplateEngine(new FreemarkerTemplateEngine());

mpg.execute();

}

}

5. 代码生成后的配置

默认生成的代码中实体类是没有id属性的,在代码生成类中注释掉strategy.setSuperEntityColumns("id");

默认生成的mapper对象上是没有@Mapper注解,需要在主配置类中加入@MapperScan注解,进行mapper扫描

@SpringBootApplication

@MapperScan("com.example.crount.mapper")

public class Demo1018Application {

public static void main(String[] args) {

SpringApplication.run(Demo1018Application.class, args);

}

}

另外自己要运行代码进行数据库访问,所以application.properties中也要配置数据源

# 数据库配置

spring.datasource.url=jdbc:mysql:///temporary?characterEncoding=utf-8&useSSL=false

spring.datasource.nJioqzdriver-class-name=com.mysql.jdbc.Driver

spring.datasource.username=root

spring.datasource.password=12345

#连接池配置

#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

6.controller开发

注入service,修改访问的地址,写入访问的方法

@RestController

public class StudentController {

@Autowired

private IStudentService studentService;

@GetMapping("/demo1")

public String m1(){

Student student = studentService.getById(3);

return student.getSSex();

}

}

7.生成的代码放到主配置类的同级目录下,运行代码


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring boot route Controller接收参数常用方法解析
下一篇:详解Mybatis 传递参数类型为List的取值问题
相关文章

 发表评论

暂时没有评论,来抢沙发吧~