isSmallFish 发表于 2024-7-22 14:56

PDMAN 自定义根据数据库生成类与文件

本帖最后由 isSmallFish 于 2024-7-22 15:01 编辑

每次建表后生成实体类很累, 还要写注解 注释, mapper.xml,尤其一个表几十上百字段时更烦了, 当然也有MybatisCodeHelper, mybaties+等插件可以玩, 但是觉得不够爽快, 于是研究了一下PDMAN, 手写生成语句, 完成数据库到项目的一键生成.
1.安装PDMAN和连接数据库, 这个就不赘叙了, 这里主要讲生成项目代码
2.PDMAN自带模板有一些, 可以自己选用
3.题主自用代码块
entity
{{var today=new Date();    var fullYear=today.getFullYear();
    var month=today.getMonth() + 1;
    var days=today.getDate();
   
    var pkVarName = "undefinedId";
    var pkVarNames = "undefinedIds";
    var pkVarNameU = "UndefinedId";
    var pkFieldKey = "UNDEFINED";
    var pkDataType = "String";
    it.entity.fields.forEach(function(field){
      if(field.primaryKey){
            pkFieldKey = field.defKey;
            pkVarName = it.func.camel(field.defKey,false);
            pkVarNames = pkVarName + "s";
            pkVarNameU = it.func.camel(field.defKey,true);
            pkDataType = field["type"];
            return;
      }
    });
    var pkgName = it.entity.env.base.nameSpace;
    var toLowerName = pkgName.slice(28);
    var controllerPkg = pkgName.slice(0,23);
    var apiName = pkgName.slice(0,24)+"api."+pkgName.slice(28);
    var coreName = pkgName.slice(0,24)+"core."+pkgName.slice(28);
    var beanClass = it.entity.env.base.codeRoot;
    var beanVarName = beanClass.charAt(0).toLowerCase()+beanClass.slice(1);
    var serviceClass = beanClass+'Service';
    var serviceVarName= beanVarName+'Service';
    var mapperVarName = beanVarName+'Mapper';
    var mapperName = beanClass+'Mapper';
    var convertName = beanClass+'Convert';
    var convertVarName = beanVarName+'Convert';
    var beanClassEntity = beanClass+'Entity';
    var QueryDto = 'queryDto';
    var UpdateDto = 'updateDto';
    var InsertDto = 'insertDto';
    var Info = 'info';
    var beanClassInfo = beanClass+'Info';
    var beanClassQuery = beanClass+'QueryDto';
    var beanClassUpdate = beanClass+'UpdateDto';
    var beanClassInsert = beanClass+'InsertDto';
    var beanClassQueryName = "查询dto";
    var beanClassUpdateName = "修改dto";
    var beanClassinsertName = "新增dto";
    var entitiesName = "entities";
    var valid = "@Valid";
    var QueryById = beanVarName+"QueryById";
    var SelectPageList = beanVarName+"SelectPageList";
    var SelectList = beanVarName+"SelectList";
    var InsertData = beanVarName+"InsertData";
    var UpdateById = beanVarName+"UpdateById";
    var DeleteById = beanVarName+"DeleteById";
    var project = "IMPS";
    var author = "ld";
}}package {{=coreName}}.{{=entitiesName}};
$blankline
import com.cenboomh.basicframework.db.genid.SnowflakeIDGen;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.time.LocalDateTime;

$blankline


/**
* {{=it.entity.defName}}
*
* @AuThor {{=author}}
*/
@Data
@Builder
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "{{=it.entity.defName}}",description = "{{=it.entity.defName}}")
@Table(name = "{{=it.entity.defKey}}")
public class {{=beanClass}}Entity implements Serializable{
    private static final long serialVersionUID = 1L;
$blankline
{{~it.entity.fields:field:index}}
    /** {{=it.func.join(field.defName,field.comment,';')}} */
    {{? field.primaryKey }}
    @Id
    @KeySql(genId = SnowflakeIDGen.class)
    {{?}}
    @ApiModelProperty(name = "{{=field.defName}}" , notes = "{{=field.defName}}")
    private {{? field.type=="VARCHAR2" }}String{{?? field.type=="DATE"}}LocalDateTime{{?? field.type=="Date"}}LocalDateTime{{?? field.type=="NUMBER"}}Integer{{??}}{{=field.type}}{{?}} {{=it.func.camel(field.defKey,false)}};
$blankline
{{~}}
$blankline
}

mapper
{{var today=new Date();
    var fullYear=today.getFullYear();
    var month=today.getMonth() + 1;
    var days=today.getDate();
   
    var pkVarName = "undefinedId";
    var pkVarNames = "undefinedIds";
    var pkVarNameU = "UndefinedId";
    var pkFieldKey = "UNDEFINED";
    var pkDataType = "String";
    it.entity.fields.forEach(function(field){
      if(field.primaryKey){
            pkFieldKey = field.defKey;
            pkVarName = it.func.camel(field.defKey,false);
            pkVarNames = pkVarName + "s";
            pkVarNameU = it.func.camel(field.defKey,true);
            pkDataType = field["type"];
            return;
      }
    });
    var pkgName = it.entity.env.base.nameSpace;
    var toLowerName = pkgName.slice(28);
    var controllerPkg = pkgName.slice(0,23);
    var apiName = pkgName.slice(0,24)+"api."+pkgName.slice(28);
    var coreName = pkgName.slice(0,24)+"core."+pkgName.slice(28);
    var beanClass = it.entity.env.base.codeRoot;
    var beanVarName = beanClass.charAt(0).toLowerCase()+beanClass.slice(1);
    var serviceClass = beanClass+'Service';
    var serviceVarName= beanVarName+'Service';
    var mapperVarName = beanVarName+'Mapper';
    var mapperName = beanClass+'Mapper';
    var convertName = beanClass+'Convert';
    var convertVarName = beanVarName+'Convert';
    var beanClassEntity = beanClass+'Entity';
    var QueryDto = 'queryDto';
    var UpdateDto = 'updateDto';
    var InsertDto = 'insertDto';
    var Info = 'info';
    var beanClassInfo = beanClass+'Info';
    var beanClassQuery = beanClass+'QueryDto';
    var beanClassUpdate = beanClass+'UpdateDto';
    var beanClassInsert = beanClass+'InsertDto';
    var beanClassQueryName = "查询dto";
    var beanClassUpdateName = "修改dto";
    var beanClassinsertName = "新增dto";
    var entitiesName = "entities";
    var valid = "@Valid";
    var QueryById = beanVarName+"QueryById";
    var SelectPageList = beanVarName+"SelectPageList";
    var SelectList = beanVarName+"SelectList";
    var InsertData = beanVarName+"InsertData";
    var UpdateById = beanVarName+"UpdateById";
    var DeleteById = beanVarName+"DeleteById";
    var project = "IMPS";
    var author = "ld";
}}package {{=coreName}}.mapper;
$blankline

import {{=apiName}}.model.dto.{{=beanClassQuery}};
import {{=coreName}}.{{=entitiesName}}.{{=beanClassEntity}};
import tk.mybatis.mapper.common.Mapper;

import java.util.List;
$blankline


/**
* {{=it.entity.defName}}
*
* @author {{=author}}
*/
public interface {{=beanClass}}Mapper extends Mapper<{{=beanClass}}Entity> {

    /**
   * 查询
   *
   * @param {{=QueryDto}} 查询入参
   * @return 记录
   */
    List<{{=beanClassInfo}}> selectList({{=beanClassQuery}} {{=QueryDto}});
}

service
{{var today=new Date();
    var fullYear=today.getFullYear();
    var month=today.getMonth() + 1;
    var days=today.getDate();
   
    var pkVarName = "undefinedId";
    var pkVarNames = "undefinedIds";
    var pkVarNameU = "UndefinedId";
    var pkFieldKey = "UNDEFINED";
    var pkDataType = "String";
    it.entity.fields.forEach(function(field){
      if(field.primaryKey){
            pkFieldKey = field.defKey;
            pkVarName = it.func.camel(field.defKey,false);
            pkVarNames = pkVarName + "s";
            pkVarNameU = it.func.camel(field.defKey,true);
            pkDataType = field["type"];
            return;
      }
    });
    var pkgName = it.entity.env.base.nameSpace;
    var toLowerName = pkgName.slice(28);
    var controllerPkg = pkgName.slice(0,23);
    var apiName = pkgName.slice(0,24)+"api."+pkgName.slice(28);
    var coreName = pkgName.slice(0,24)+"core."+pkgName.slice(28);
    var beanClass = it.entity.env.base.codeRoot;
    var beanVarName = beanClass.charAt(0).toLowerCase()+beanClass.slice(1);
    var serviceClass = beanClass+'Service';
    var serviceVarName= beanVarName+'Service';
    var mapperVarName = beanVarName+'Mapper';
    var mapperName = beanClass+'Mapper';
    var convertName = beanClass+'Convert';
    var convertVarName = beanVarName+'Convert';
    var beanClassEntity = beanClass+'Entity';
    var QueryDto = 'queryDto';
    var UpdateDto = 'updateDto';
    var InsertDto = 'insertDto';
    var Info = 'info';
    var beanClassInfo = beanClass+'Info';
    var beanClassQuery = beanClass+'QueryDto';
    var beanClassUpdate = beanClass+'UpdateDto';
    var beanClassInsert = beanClass+'InsertDto';
    var beanClassQueryName = "查询dto";
    var beanClassUpdateName = "修改dto";
    var beanClassinsertName = "新增dto";
    var entitiesName = "entities";
    var valid = "@Valid";
    var QueryById = beanVarName+"QueryById";
    var SelectPageList = beanVarName+"SelectPageList";
    var SelectList = beanVarName+"SelectList";
    var InsertData = beanVarName+"InsertData";
    var UpdateById = beanVarName+"UpdateById";
    var DeleteById = beanVarName+"DeleteById";
    var project = "IMPS";
    var author = "ld";
}}package {{=coreName}}.service;
$blankline
import com.cenboomh.basicframework.commons.domain.PageResult;
import {{=apiName}}.model.{{=beanClassInfo}};
import {{=apiName}}.model.dto.{{=beanClassQuery}};
import {{=apiName}}.model.dto.{{=beanClassUpdate}};
import {{=apiName}}.model.dto.{{=beanClassInsert}};
import {{=coreName}}.convert.{{=convertName}};
import {{=coreName}}.mapper.{{=mapperName}};
import com.cenboomh.hicor.huap.api.GatewayContextHolder;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;
$blankline
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
$blankline
/**
* {{=it.entity.defName}}({{=it.entity.defKey}})表服务实现类
*
* @author {{=author}}
*/
@Slf4j
@Service
public class {{=serviceClass}}{
    $blankline
    @Resource
    private {{=mapperName}} {{=mapperVarName}};
    $blankline
    @Resource
    private {{=convertName}} {{=convertVarName}};
    $blankline
    @Resource
    private SqlSessionFactory sqlSessionFactory;
    $blankline
    /**
   * {{=it.entity.defName}}通过ID查询单条数据
   *
   * @param {{=pkVarName}} 主键
   * @return 实例对象
   * @author {{=author}}
   */
    public {{=beanClassInfo}} {{=QueryById}}(String {{=pkVarName}}){
      return {{=convertVarName}}.convert({{=mapperVarName}}.selectByPrimaryKey({{=pkVarName}}));
    }
    $blankline

    /**
   * {{=it.entity.defName}}分页查询
   *
   * @param {{=QueryDto}} 查询信息
   * @return {@link PageResult<{{=beanClassInfo}}>} 数据集合
   * @author {{=author}}
   */
    public PageResult<{{=beanClassInfo}}> {{=SelectPageList}}({{=beanClassQuery}} {{=QueryDto}}) {
      Page<{{=beanClassInfo}}> entityPage = PageMethod.startPage({{=QueryDto}}.getPageNum(), {{=QueryDto}}.getPageSize())
                .doSelectPage(() -> {{=SelectList}}({{=QueryDto}}));
      return new PageResult<>(entityPage.getResult(), entityPage.getPageSize(), entityPage.getTotal());
    }
    $blankline
   
    /**
   * {{=it.entity.defName}}全部查询
   *
   * @param {{=QueryDto}} 查询信息
   * @return {@link PageResult<{{=beanClassInfo}}>} 数据集合
   * @author {{=author}}
   */
    public List<{{=beanClassInfo}}> {{=SelectList}}({{=beanClassQuery}} {{=QueryDto}}) {
      return {{=mapperVarName}}.selectList({{=QueryDto}});
    }
    $blankline
    /**
   * {{=it.entity.defName}}新增数据
   *
   * @param {{=InsertDto}} 实例对象
   * @return int 是否成功
   * @author {{=author}}
   */
    @Transactional(rollbackFor = Throwable.class)
    public int {{=InsertData}}({{=beanClassInsert}} {{=InsertDto}}){
      return {{=mapperVarName}}.insertSelective(
            {{=convertVarName}}.insertConvertEntity({{=InsertDto}})
                .setCreateBy(GatewayContextHolder.get().getUserId())
                .setCreateTime(LocalDateTime.now())
      );
    }
    $blankline
    /**
   * {{=it.entity.defName}}更新数据
   *
   * @param {{=UpdateDto}} 实例对象
   * @return int 是否成功
   * @author {{=author}}
   */
    @Transactional(rollbackFor = Throwable.class)
    public int {{=UpdateById}}({{=beanClassUpdate}} {{=UpdateDto}}){
      return {{=mapperVarName}}.updateByPrimaryKeySelective(
            {{=convertVarName}}.updateConvertEntity({{=UpdateDto}})
                .setUpdateBy(GatewayContextHolder.get().getUserId())
                .setUpdateTime(LocalDateTime.now())
      );
    }
    $blankline
    /**
   * {{=it.entity.defName}}通过主键删除数据
   *
   * @param {{=pkVarNames}} 主键
   * @author {{=author}}
   */
    @Transactional(rollbackFor = Throwable.class)
    public void {{=DeleteById}}(String {{=pkVarNames}}){
      batchDeleteByIds(Arrays.asList({{=pkVarNames}}.split(",")));
    }
    $blankline
    /**
   * 批量删除
   *
   * @param {{=pkVarNames}} 主键
   */
    @Transactional(rollbackFor = Throwable.class)
    public void batchDeleteByIds(List<String> {{=pkVarNames}}) {
      List<List<String>> partition = Lists.partition({{=pkVarNames}}, 200);
      if (ObjectUtils.isNotEmpty(partition)) {
            try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, Boolean.FALSE)) {
                {{=mapperName}} mapper = sqlSession.getMapper({{=mapperName}}.class);
                partition.forEach(l -> {
                  l.forEach(mapper::deleteByPrimaryKey);
                  sqlSession.commit();
                  sqlSession.clearCache();
                });
            }
      }
    }
}

效果图
package core..service;

import com.cenboomh.basicframework.commons.domain.PageResult;
import api..model.BmsInvRecordInfo;
import api..model.dto.BmsInvRecordQueryDto;
import api..model.dto.BmsInvRecordUpdateDto;
import api..model.dto.BmsInvRecordInsertDto;
import core..convert.BmsInvRecordConvert;
import core..mapper.BmsInvRecordMapper;
import com.cenboomh.hicor.huap.api.GatewayContextHolder;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
* ****表服务实现类
*
* @author ld
*/
@Slf4j
@Service
public class BmsInvRecordService{
   
    @Resource
    private BmsInvRecordMapper bmsInvRecordMapper;
   
    @Resource
    private BmsInvRecordConvert bmsInvRecordConvert;
   
    @Resource
    private SqlSessionFactory sqlSessionFactory;
   
    /**
   * *****
   *
   * @param id 主键
   * @return 实例对象
   * @author ld
   */
    public BmsInvRecordInfo bmsInvRecordQueryById(String id){
      return bmsInvRecordConvert.convert(bmsInvRecordMapper.selectByPrimaryKey(id));
    }
   
    /**
   * *****
   *
   * @param queryDto 查询信息
   * @return {@link PageResult<BmsInvRecordInfo>} 数据集合
   * @author ld
   */
    public PageResult<BmsInvRecordInfo> bmsInvRecordSelectPageList(BmsInvRecordQueryDto queryDto) {
      Page<BmsInvRecordInfo> entityPage = PageMethod.startPage(queryDto.getPageNum(), queryDto.getPageSize())
                .doSelectPage(() -> bmsInvRecordSelectList(queryDto));
      return new PageResult<>(entityPage.getResult(), entityPage.getPageSize(), entityPage.getTotal());
    }
   
    /**
   * *****
   *
   * @param queryDto 查询信息
   * @return {@link PageResult<BmsInvRecordInfo>} 数据集合
   * @author ld
   */
    public List<BmsInvRecordInfo> bmsInvRecordSelectList(BmsInvRecordQueryDto queryDto) {
      return bmsInvRecordMapper.selectList(queryDto);
    }
   
    /**
   * *****
   *
   * @param insertDto 实例对象
   * @return int 是否成功
   * @author ld
   */
    @Transactional(rollbackFor = Throwable.class)
    public int bmsInvRecordInsertData(BmsInvRecordInsertDto insertDto){
      return bmsInvRecordMapper.insertSelective(
            bmsInvRecordConvert.insertConvertEntity(insertDto)
                .setCreateBy(GatewayContextHolder.get().getUserId())
                .setCreateTime(LocalDateTime.now())
      );
    }
   
    /**
   * *****
   *
   * @param updateDto 实例对象
   * @return int 是否成功
   * @author ld
   */
    @Transactional(rollbackFor = Throwable.class)
    public int bmsInvRecordUpdateById(BmsInvRecordUpdateDto updateDto){
      return bmsInvRecordMapper.updateByPrimaryKeySelective(
            bmsInvRecordConvert.updateConvertEntity(updateDto)
                .setUpdateBy(GatewayContextHolder.get().getUserId())
                .setUpdateTime(LocalDateTime.now())
      );
    }
   
    /**
   * *****
   *
   * @param ids 主键
   * @author ld
   */
    @Transactional(rollbackFor = Throwable.class)
    public void bmsInvRecordDeleteById(String ids){
      batchDeleteByIds(Arrays.asList(ids.split(",")));
    }
   
    /**
   * 批量删除
   *
   * @param ids 主键
   */
    @Transactional(rollbackFor = Throwable.class)
    public void batchDeleteByIds(List<String> ids) {
      List<List<String>> partition = Lists.partition(ids, 200);
      if (ObjectUtils.isNotEmpty(partition)) {
            try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, Boolean.FALSE)) {
                BmsInvRecordMapper mapper = sqlSession.getMapper(BmsInvRecordMapper.class);
                partition.forEach(l -> {
                  l.forEach(mapper::deleteByPrimaryKey);
                  sqlSession.commit();
                  sqlSession.clearCache();
                });
            }
      }
    }
}

isSmallFish 发表于 2024-7-22 14:59

理论上这不属于JAVA 属于dot.js, 所以可以生成所有语言的entity与mapper等数据文件, 目前题主根据业务表生成的所有代码是可以玩的

newdriver 发表于 2024-7-22 17:06

赞一个!
页: [1]
查看完整版本: PDMAN 自定义根据数据库生成类与文件