使用MybatisPlus生成数据库表

使用MybatisPlus生成数据库表

创建一个springboot项目。

pom文件

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.9</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.pan</groupId>
    <artifactId>generate-code</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>generate-code</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.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.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>

        <!-- 代码自动生成器依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

生成代码的工具类

package com.pan.generCode;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * @PackageName: com.pan.generCode
 * @ClassName: generCode
 * @author: zhangpan
 * @data: 2023/3/14 23:38
 */
public class generCode {

    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");
        gc.setOutputDir(projectPath + "/src/main/java");//设置代码生成路径
        gc.setFileOverride(true);//是否覆盖以前文件
        gc.setOpen(false);//是否打开生成目录
        gc.setAuthor("zhangpan");//设置项目作者名称
        gc.setIdType(IdType.AUTO);//设置主键策略
        gc.setBaseResultMap(true);//生成基本ResultMap
        gc.setBaseColumnList(true);//生成基本ColumnList
        gc.setServiceName("%sService");//去掉服务默认前缀
        gc.setDateType(DateType.ONLY_DATE);//设置时间类型
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.pan");
        pc.setMapper("mapper");
        pc.setXml("mapper.xml");
        pc.setEntity("pojo");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        // 策略配置
        StrategyConfig sc = new StrategyConfig();
        sc.setNaming(NamingStrategy.underline_to_camel);
        sc.setColumnNaming(NamingStrategy.underline_to_camel);
        sc.setEntityLombokModel(true);//自动lombok
        sc.setRestControllerStyle(true);
        sc.setControllerMappingHyphenStyle(true);

        sc.setLogicDeleteFieldName("deleted");//设置逻辑删除

        //设置自动填充配置
        TableFill gmt_create = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmt_modified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills=new ArrayList<>();
        tableFills.add(gmt_create);
        tableFills.add(gmt_modified);
        sc.setTableFillList(tableFills);

        //乐观锁
        sc.setVersionFieldName("version");
        sc.setRestControllerStyle(true);//驼峰命名



        //  sc.setTablePrefix("tbl_"); 设置表名前缀
        sc.setInclude(scanner("表名,多个英文逗号分割").split(","));
        mpg.setStrategy(sc);

        // 生成代码
        mpg.execute();

    }


}

添加配置

application

#datasource
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/shiro?characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456
mybatis-plus:
  mapper-locations: classpath*:com/pan/mapper/xml/*Mapper.xml
  type-aliases-package: com.pan.mapper

启动控制类

package com.pan;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @PackageName: com.pan
 * @ClassName: codeApplication
 * @author: zhangpan
 * @data: 2023/3/14 23:37
 */
@MapperScan("com.pan.mapper") //扫描mapper文件夹
@SpringBootApplication
public class codeApplication {
    public static void main(String[] args) {
        SpringApplication.run(codeApplication.class,args);
    }
}

生成代码后的基本使用

实体类

package com.pan.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.Version;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author zhangpan
 * @since 2023-03-15
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class TUser implements Serializable {

    private static final long serialVersionUID = 1L;

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

    private String username;

    private String password;

    private String salt;


}

mapper

package com.pan.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pan.pojo.TUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author zhangpan
 * @since 2023-03-15
 */
public interface TUserMapper extends BaseMapper<TUser> {

}

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.pan.mapper.TUserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.pan.pojo.TUser">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
        <result column="salt" property="salt" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, username, password, salt
    </sql>

</mapper>

service

package com.pan.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pan.pojo.TUser;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author zhangpan
 * @since 2023-03-15
 */
public interface TUserService extends IService<TUser> {
    int insertUser(TUser user );
    int updateUser(TUser user );
    int deleteUser(TUser user );
    TUser getUserByName(String userName );
    IPage getUserPage(Page page, TUser user );

}

impl

package com.pan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pan.pojo.TUser;
import com.pan.mapper.TUserMapper;
import com.pan.service.TUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangpan
 * @since 2023-03-15
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Autowired(required = false)
    private TUserMapper userMapper;

    @Override
    public int insertUser(TUser user) {
        return userMapper.insert(user);
    }

    @Override
    public int updateUser(TUser user) {
        return userMapper.updateById(user);
    }

    @Override
    public int deleteUser(TUser user) {
        return userMapper.deleteById(user.getId());
    }

    @Override
    public TUser getUserByName(String userName) {
        return userMapper.selectOne(new QueryWrapper<TUser>().eq("username",userName));
    }

    @Override
    public IPage getUserPage(Page page, TUser user) {
        return baseMapper.getUserPage(page,user);
    }
}

controller

package com.pan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pan.pojo.TUser;
import com.pan.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangpan
 * @since 2023-03-15
 */
@RestController
@RequestMapping("/t-user")
public class TUserController {

    @Autowired
    private TUserService userService;

    // 增
    @PostMapping( value = "/insert")
    public Object insert(@RequestBody TUser user ) {
        return userService.insertUser(user);
    }

    // 删
    @DeleteMapping(value = "/delete")
    public Object delete(@RequestBody TUser user ) {
        return userService.deleteUser(user);
    }

    // 改
    @PutMapping( value = "/update")
    public Object update(@RequestBody TUser user ) {
        return userService.updateUser(user);
    }

    // 查
    @GetMapping(value = "/getUserByName")
    public Object getUserByName(@RequestParam String userName ) {
        return userService.getUserByName(userName);
    }

    @GetMapping( value = "/page")
    public Object getUserPage(Page page, TUser user ) {
        Page page1 = userService.page(page, new QueryWrapper<>(user));
        long current = page1.getCurrent();
        System.out.println("页号current:"+current);
        long pages = page1.getPages();
        System.out.println("总页数pages:"+pages);
        List records = page1.getRecords();
        System.out.println("数据records:"+records);
        long size = page1.getSize();
        System.out.println("size:"+size);
        long total = page1.getTotal();
        System.out.println("total:"+total);
        return page1;
    }

}
您好!对于MyBatis Plus和达梦数据库的代码生成,可以按照以下步骤进行操作: 1. 首先,您需要在项目中引入MyBatis Plus和达梦数据库的相关依赖。可以在项目的pom.xml文件中添加相应的依赖。 2. 在项目的配置文件中,配置数据源和MyBatis Plus的相关配置。确保数据库连接正确,并且已经正确配置了MyBatis Plus。 3. 接下来,您可以使用MyBatis Plus的代码生成器来生成达梦数据库的代码。MyBatis Plus提供了一个名为AutoGenerator的类来进行自动代码生成。 首先,您需要创建一个AutoGenerator对象,并配置相关参数,如数据源、包名、作者等信息。 然后,您可以通过调用AutoGenerator对象的setGlobalConfig方法来配置全局的代码生成策略,如生成文件路径、是否覆盖已有文件等。 接着,您可以通过调用AutoGenerator对象的setDataSource方法来设置数据源。 最后,通过调用AutoGenerator对象的包含generate方法来执行代码生成。 示例代码如下所示: ```java public class CodeGenerator { public static void main(String[] args) { // 代码生成器 AutoGenerator generator = new AutoGenerator(); // 全局配置 GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java"); globalConfig.setAuthor("YourName"); // 更多配置... generator.setGlobalConfig(globalConfig); // 数据源配置 DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.DM); dataSourceConfig.setUrl("jdbc:dm://localhost:5236/your_database"); dataSourceConfig.setUsername("your_username"); dataSourceConfig.setPassword("your_password"); // 更多配置... generator.setDataSource(dataSourceConfig); // 包配置 PackageConfig packageConfig = new PackageConfig(); packageConfig.setParent("com.example.demo"); // 更多配置... generator.setPackageInfo(packageConfig); // 执行生成 generator.execute(); } } ``` 4. 运行上述代码,即可生成达梦数据库对应的实体类、Mapper接口等代码。 请注意,以上代码仅为示例,您需要根据自己的项目需求进行相应的配置和调整。另外,可能还需要根据项目的具体情况进行一些其他的配置和调整,如名映射策略、字段映射策略等。 希望以上信息对您有所帮助!如有任何疑问,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值