springboot整合Mybatis-Plus 实现代码生成增删改查

springboot整合Mybatis-Plus 实现代码生成增删改查

spring boot 2.x
用user_plus表为实例

sql结构

CREATE TABLE `user_plus` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

pom文件

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
   		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.3</version>
        </dependency>
		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.5</version>
        </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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
	<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.yml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

application文件

server:
  port: 9999
spring:
  application:
    name: springboot-mybatisPlus
  # database 部分注释
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/xxxx?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconect=true&serverTimezone=GMT%2b8
    username: xxxx
    password: xxxx
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 50
    initialSize: 0
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 1 from dual
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
    removeAbandoned: true
    removeAbandonedTimeout: 180
mybatis-plus:
  global-config:
    # 逻辑删除配置
    db-config:
      # 删除前
      logic-not-delete-value: 1
      # 删除后
      logic-delete-value: 0
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:mybatisplus/mapper/*.xml

设置Mybatis-Plus分页

/**
 * 配置分页插件
 * mybatis - plus分页插件MybatisPlusConfig:
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        //设置方言类型
        page.setDialectType("mysql");
        return page;
    }
}

代码生成工具,自行改动生成代码的存放位置

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.isNotEmpty(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");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("vicente");
        gc.setOpen(false);
        // service 命名方式
        gc.setServiceName("%sService");
        // service impl 命名方式
        gc.setServiceImplName("%sServiceImpl");
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/springboot-test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("cn.theone.tmp.mybatisplus");
        pc.setEntity("model");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        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";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                String moduleName = pc.getModuleName() == null ? "" : pc.getModuleName();
                return projectPath + "/src/main/resources/mybatisplus/mapper/" + moduleName
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT + "xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

这是我的完整目录结构,怕出错的朋友可以按照此目录操作
在这里插入图片描述
启动类加上扫描mapper注解

@MapperScan("cn.theone.tmp.mybatisplus.mapper")

实体类

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("user_plus")
public class UserPlus extends Model<UserPlus> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;


    @Override
    protected Serializable pkVal() {
        return this.id;
    }

}

Mapper类

//默认是没有Repository注解和findAll方法的,接口可以自行扩展
@Repository
public interface UserPlusMapper extends BaseMapper<UserPlus> {

    List<UserPlus> findAll();
}

Service接口和实现类

//接口
public interface UserPlusService extends IService<UserPlus> {

    List<UserPlus> findAll();
}

//实现
@Service
@Transactional(rollbackFor = Exception.class)
public class UserPlusServiceImpl extends ServiceImpl<UserPlusMapper, UserPlus> implements UserPlusService {

    @Autowired
    private UserPlusMapper userPlusMapper;

    @Override
    public List<UserPlus> findAll() {
        return userPlusMapper.findAll();
    }
}

Mapper.xml类,默认是没有findAll方法的,自行扩展的接口

<?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="cn.theone.tmp.mybatisplus.mapper.UserPlusMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="cn.theone.tmp.mybatisplus.model.UserPlus">
        <id column="id" property="id" />
        <result column="name" property="name" />
    </resultMap>
    <select id="findAll" resultType="cn.theone.tmp.mybatisplus.model.UserPlus">
        select * from user_plus
    </select>

</mapper>

写测试类测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TmpApplication.class)
public class mybatisPlusTest {

    @Autowired
    private UserPlusService userPlusService;

    @Test
    public void findById() {
        UserPlus userPlus = userPlusService.selectById(4);
        System.out.println(userPlus.getName());
    }

    @Test
    public void add() {
        UserPlus user = new UserPlus();
        user.setName("李四1");
        userPlusService.insert(user);
    }

    @Test
    public void update(){
        UserPlus user = new UserPlus();
        user.setId(4);
        user.setName("李四111");
        userPlusService.updateById(user);
    }

    @Test
    public void delete(){
        userPlusService.deleteById(4);
    }


    @Test
    public void findAll(){
        List<UserPlus> userList = userPlusService.findAll();
        for (UserPlus user : userList) {
            System.out.println(user.getName());
        }
    }
}

默认Mybatis-Plus已经有非常全面的接口了,可以满足大部分要求,有满足不了的需求可以直接扩展接口xml中写sql即可
在这里插入图片描述

至此Spring boot整合Mybatis-Plus 就完毕了,有什么问题可以提出来,对您有帮助欢迎评论区支持一下

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,需要在后端环境中搭建好 Spring Boot 和 MyBatis Plus 的开发环境,可以使用 Maven 或 Gradle 等构建工具来引入所需的依赖。 接下来,需要创建一个数据表对应的 Java 实体类,并使用 MyBatis Plus 提供的注解来标识表名、主键、字段等信息。例如: ``` @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; } ``` 然后,创建一个 Mapper 接口,继承自 MyBatis Plus 提供的 BaseMapper 接口,用于定义增删改查等基本操作。例如: ``` public interface UserMapper extends BaseMapper<User> { } ``` 在 Spring Boot 的配置文件中,配置数据库连接信息和 MyBatis Plus 相关配置,例如: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis-plus.configuration.map-underscore-to-camel-case=true ``` 最后,在 Spring Boot 中创建一个 Controller 类,定义对应的请求处理方法,例如: ``` @RestController @RequestMapping("/user") public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/{id}") public User getUserById(@PathVariable("id") Long id) { return userMapper.selectById(id); } @PostMapping("") public void createUser(@RequestBody User user) { userMapper.insert(user); } @PutMapping("/{id}") public void updateUser(@PathVariable("id") Long id, @RequestBody User user) { user.setId(id); userMapper.updateById(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable("id") Long id) { userMapper.deleteById(id); } } ``` 这样,就完成了 Vue 和 Spring Boot 整合 MyBatis Plus 做增删改查的基本流程。在前端中,可以使用 Axios 等 HTTP 请求库来调用后端的接口。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值