当前位置: 首页 > news >正文

demo测试

目录

  • 接口
  • common
    • CodeGenerator
  • entity
    • user
  • mapper
    • UserMapper
  • controller
    • UserController
  • service
    • UserService
    • impl
      • UserServiceImpl
  • mapper.xml
  • pom.xml
  • application.yml

接口

在这里插入图片描述

common

CodeGenerator

package com.llz.demo.common;import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CodeGenerator {/*** <p>* 读取控制台内容* </p>*/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 + "!");}/*** 操作步骤:* 1.修改数据源包括地址密码信息,对应代码标记:⼀、 下同* 2.模块配置,可以修改包名* 3.修改模板(这步可忽略)* @param args*/public static void main(String[] args) {// 代码⽣成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir")+"/";System.out.println(projectPath);gc.setOutputDir(projectPath + "/src/main/java");gc.setAuthor("demo");gc.setOpen(false);gc.setSwagger2(true); //实体属性 Swagger2 注解gc.setBaseResultMap(true);// XML ResultMapgc.setBaseColumnList(true);// XML columList//去掉service接⼝⾸字⺟的I, 如DO为User则叫UserServicegc.setServiceName("%sService");mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();// ⼀、修改数据源dsc.setUrl("jdbc:mysql://localhost:3306/wms?useUnicode=true&characterEncoding=UTF8&useSSL=false");// dsc.setSchemaName("public");
//                dsc.setDriverName("com.mysql.jdbc.Driver");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();//pc.setModuleName(scanner("模块名"));// ⼆、模块配置pc.setParent("com.llz.demo").setEntity("entity").setMapper("mapper").setService("service").setServiceImpl("service.impl").setController("controller");mpg.setPackageInfo(pc);// ⾃定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};// 如果模板引擎是 freemarkerString templatePath = "templates/mapper.xml.ftl";// 如果模板引擎是 velocity// String templatePath = "/templates/mapper.xml.vm";// ⾃定义输出配置List<FileOutConfig> focList = new ArrayList<>();// ⾃定义配置会被优先输出focList.add(new FileOutConfig(templatePath) {@Overridepublic String outputFile(TableInfo tableInfo) {// ⾃定义输出⽂件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发⽣变化!!return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()+ "/" + tableInfo.getEntityName() + "Mapper" +StringPool.DOT_XML;}});/*cfg.setFileCreate(new IFileCreate() {@Overridepublic boolean isCreate(ConfigBuilder configBuilder, FileType fileType,
String filePath) {// 判断⾃定义⽂件夹是否需要创建checkDir("调⽤默认⽅法创建的⽬录,⾃定义⽬录⽤");if (fileType == FileType.MAPPER) {// 已经⽣成 mapper ⽂件判断存在,不想重新⽣成返回 falsereturn !new File(filePath).exists();}// 允许⽣成模板⽂件return true;}});*/cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);//3. ⽣成代码并测试//四、实现增删改查// 配置模板TemplateConfig templateConfig = new TemplateConfig();// 配置⾃定义输出模板//指定⾃定义模板路径,注意不要带上.ftl/.vm, 会根据使⽤的模板引擎⾃动识别// 三、修改模板/*templateConfig.setEntity("templates/entity2.java");templateConfig.setService("templates/service2.java");templateConfig.setController("templates/controller2.java");templateConfig.setMapper("templates/mapper2.java");templateConfig.setServiceImpl("templates/serviceimpl2.java");*/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.setSuperEntityClass("BaseEntity");strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);// 公共⽗类//strategy.setSuperControllerClass("BaseController");// strategy.setSuperControllerClass("你⾃⼰的⽗类控制器,没有就不⽤设置!");// 写于⽗类中的公共字段// strategy.setSuperEntityColumns("id");strategy.setInclude(scanner("表名,多个英⽂逗号分割").split(","));strategy.setControllerMappingHyphenStyle(true);//strategy.setTablePrefix(pc.getModuleName() + "_");// 忽略表前缀tb_,⽐如说tb_user,直接映射成user对象// 四、注意是否要去掉表前缀//strategy.setTablePrefix("tb_");mpg.setStrategy(strategy);mpg.setTemplateEngine(new FreemarkerTemplateEngine());mpg.execute();}
}

entity

user

package com.llz.demo.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;/*** <p>* * </p>** @author demo* @since 2024-08-14*/
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="User对象", description="")
public class User implements Serializable {private static final long serialVersionUID = 1L;@ApiModelProperty(value = "主键")@TableId(value = "id", type = IdType.AUTO)private Integer id;@ApiModelProperty(value = "账号")private String no;@ApiModelProperty(value = "姓名")private String name;@ApiModelProperty(value = "密码")private String password;@ApiModelProperty(value = "年龄")private Integer age;@ApiModelProperty(value = "性别, 0-女, 1-男")private Integer sex;@ApiModelProperty(value = "手机号")private String phone;@ApiModelProperty(value = "角色, 0-超级管理员, 1-管理员, 2-用户")private Integer roleId;@ApiModelProperty(value = "是否有效,Y有效,其他无效")@TableField("isValid")private String isvalid;}

mapper

UserMapper

package com.llz.demo.mapper;import com.llz.demo.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;import javax.annotation.Resource;/*** <p>*  Mapper 接口* </p>** @author demo* @since 2024-08-14*/
@Mapper
public interface UserMapper extends BaseMapper<User> {}

controller

UserController

package com.llz.demo.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.llz.demo.common.QueryPageParam;
import com.llz.demo.entity.User;
import com.llz.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;/*** <p>*  前端控制器* </p>** @author demo* @since 2024-08-14*/
@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;
//    查询@GetMapping("/list")public List<User> list(){return userService.list();}//    删除@GetMapping("/delete")public boolean delete(Integer id){return userService.removeById(id);}//    新增@PostMapping("/save")public boolean save(@RequestBody User user){return userService.save(user);}
//    修改@PostMapping("/mod")public boolean mod(@RequestBody User user){return userService.updateById(user);}@PostMapping("/saveOrmod")public boolean saveOrmod(@RequestBody User user){return userService.saveOrUpdate(user);}
//      模糊匹配@PostMapping("/listP")public List<User> listP(@RequestBody User user){LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();lambdaQueryWrapper.like(User::getName,user.getName());return userService.list(lambdaQueryWrapper);}@PostMapping("/listPage")public List<User> listPage(@RequestBody QueryPageParam query){System.out.println(query);System.out.println("num==="+query.getPageNum());System.out.println("size==="+query.getPageSize());System.out.println("param==="+query.getParam());}}

service

UserService

package com.llz.demo.service;import com.llz.demo.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;/*** <p>*  服务类* </p>** @author demo* @since 2024-08-14*/
public interface UserService extends IService<User> {}

impl

UserServiceImpl

package com.llz.demo.service.impl;import com.llz.demo.entity.User;
import com.llz.demo.mapper.UserMapper;
import com.llz.demo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;/*** <p>*  服务实现类* </p>** @author demo* @since 2024-08-14*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}

mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.llz.demo.mapper.UserMapper"><!-- 通用查询映射结果 --><resultMap id="BaseResultMap" type="com.llz.demo.entity.User"><id column="id" property="id" /><result column="no" property="no" /><result column="name" property="name" /><result column="password" property="password" /><result column="age" property="age" /><result column="sex" property="sex" /><result column="phone" property="phone" /><result column="role_id" property="roleId" /><result column="isValid" property="isvalid" /></resultMap><!-- 通用查询结果列 --><sql id="Base_Column_List">id, no, name, password, age, sex, phone, role_id, isValid</sql></mapper>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.llz</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>demo</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.6.13</spring-boot.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope></dependency><!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.1</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.4.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.30</version></dependency><dependency><groupId>com.spring4all</groupId><artifactId>spring-boot-starter-swagger</artifactId><version>1.5.1.RELEASE</version></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>${spring-boot.version}</version><configuration><mainClass>com.llz.demo.DemoApplication</mainClass><skip>true</skip></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build></project>

application.yml

server:port: 8090spring:datasource:url: jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8username: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
http://www.lryc.cn/news/425706.html

相关文章:

  • TinTinLand Web3 + DePIN 共学月|深入探索 DePIN 项目,全景分析去中心化网络未来
  • Java并发编程(六)
  • k8s对外服务之Ingress
  • 使用Python+moviepy在视频画面上绘制边框
  • 灵办AI探索之旅:颠覆传统的代码开发工具
  • 【Redis】Redis 数据类型与结构—(二)
  • Tomcat初篇
  • 机器学习(2)-- KNN算法之手写数字识别
  • 【机器人】关于钉钉机器人如何进行自定义开发问答【详细清晰】
  • Qt:exit,quit,close的用法及区别
  • Linux——进程地址空间
  • 信创(国产化)方案
  • EasyRecovery17中文版永久汉化版电脑数据恢复工具下载
  • Cesium倾斜相机视角观察物体
  • C/C++开发---全篇
  • Android全面解析之context机制(二): 从源码角度分析context创建流程(上)
  • WPS真题题库导入刷题小程序:百思考个人使用经验分享
  • 拯救者双系统问题 Verifiying shim SBAT data failed: Security Policy Violation
  • ThreeJs学习笔记--坐标系,光源,相机控件
  • 基于 Android studio 实现停车场管理系统--原创
  • 8 个最佳 Java IDE 和文本编辑器
  • 【2024最新版版】PyCharm安装教程
  • 奥运科技观察:AI PC,如何成为当代体育精神的数字捍卫者?
  • Java进阶篇之包的概念及其应用
  • 短剧出海,赚钱新途径,掌握海外短剧CPS分销的秘诀
  • uniapp小程序openid和unionId
  • 前端工程化-04.Vue项目简介
  • 10 Checkbutton 组件
  • 获奖方案|趋动科技:资源池化释放AI算力价值
  • Gin框架接入pyroscope完美替代pprof实现检测内存泄露