Springboot 整合Mybatis-generator和pagehelper

首先搭建一个springboot 项目(这里不再叙述,具体看springboot小结)

首先 引入依赖:

    
    
        com.github.pagehelper
        pagehelper-spring-boot-starter
        ${mybatisPageHelper.version}
    

    
    
        org.mybatis.generator
        mybatis-generator-core
        1.3.6
        test
    
    
        junit
        junit
        test
    

然后 在test包下面创建:
mapper包:
创建类MybatisGeneratorCodeTest
/**
* Mybatis代码生成
* @author
* @version 1.0.0
*/
public class MybatisGeneratorCodeTest {

    static final Logger LOG = LoggerFactory.getLogger(MybatisGeneratorCodeTest.class);

    @Test
    public void run() {
        List warnings = new ArrayList();
        boolean overwrite = true;

        List configFileList = new ArrayList<>();
        configFileList.add("/generatorConfig-canyin.xml");

        configFileList.stream().forEach((configFile) -> {
            try {
                Resource resource = new ClassPathResource(configFile);
                ConfigurationParser cp = new ConfigurationParser(warnings);
                Configuration config = cp.parseConfiguration(resource.getFile());
                DefaultShellCallback callback = new DefaultShellCallback(overwrite);
                MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
                myBatisGenerator.generate(null);
            } catch (Exception e) {
                LOG.error("mybatis generator code error!", e);
                throw new RuntimeException(e);
            }
        });
    }
}

创建plugin包
/**
* Mybatis代码注释生成
* @author
* @version 1.0.0
*/
public class MybatisCommentGenerator extends DefaultCommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String currentDateStr;

    public MybatisCommentGenerator() {
        super();
        properties = new Properties();
        systemPro = System.getProperties();
        suppressDate = false;
        suppressAllComments = false;
        currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        return;
    }

    @Override
    public void addComment(XmlElement xmlElement) {
        //      StringBuilder sb = new StringBuilder();
        //      sb.append(MergeConstants.NEW_ELEMENT_TAG);
        //
        //      xmlElement.addElement(new TextElement(""));
    }

    @Override
    public void addRootComment(XmlElement rootElement) {
        return;
    }

    @Override
    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);
        suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
        suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
    }

    @Override
    protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }
        javaElement.addJavaDocLine(" *");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge");
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    @Override
    protected String getDateString() {
        String result = "";
        if (!suppressDate) {
            result = currentDateStr;
        }
        return result;
    }

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        innerClass.addJavaDocLine("/**");
        innerClass.addJavaDocLine(" * " + introspectedTable.getRemarks());
        innerClass.addJavaDocLine(" * 数据库表:" + introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(" * @date " + getDateString());
        innerClass.addJavaDocLine(" * @author Mybatis Generator");
        innerClass.addJavaDocLine(" */");
    }

    @Override
    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerEnum.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString().replace("\n", " "));
        innerEnum.addJavaDocLine(" */");
    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("/** ");
        sb.append(introspectedColumn.getRemarks());
        sb.append(" */");
        field.addJavaDocLine(sb.toString());
    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("/** ");
        String fieldName = field.getName();
        if ("orderByClause".equals(fieldName)) {
            sb.append(" 排序字段");
        } else if ("distinct".equals(fieldName)) {
            sb.append(" 过滤重复数据");
        } else if ("oredCriteria".equals(fieldName)) {
            sb.append(" 当前的查询条件实例");
        } else if ("isDistinct".equals(fieldName)) {
            sb.append(" 是否过滤重复数据");
        }
        sb.append(" */");
        field.addJavaDocLine(sb.toString());
    }

    @Override
    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
        StringBuilder sb = new StringBuilder();
        method.addJavaDocLine("/**");
        sb.append(" * ");
        if (method.isConstructor()) {
            sb.append(" 构造查询条件");
        }

        final List parameterList = method.getParameters();
        String methodName = method.getName();
        if ("setOrderByClause".equals(methodName)) {
            sb.append(" 设置排序字段");
        } else if ("setDistinct".equals(methodName)) {
            sb.append(" 设置过滤重复数据");
        } else if ("getOredCriteria".equals(methodName)) {
            sb.append(" 获取当前的查询条件实例");
        } else if ("isDistinct".equals(methodName)) {
            sb.append(" 是否过滤重复数据");
        } else if ("getOrderByClause".equals(methodName)) {
            sb.append(" 获取排序字段");
        } else if ("createCriteria".equals(methodName)) {
            sb.append(" 创建一个查询条件");
        } else if ("createCriteriaInternal".equals(methodName)) {
            sb.append(" 内部构建查询条件对象");
        } else if ("clear".equals(methodName)) {
            sb.append(" 清除查询条件");
        } else if ("countByExample".equals(methodName)) {
            sb.append(" 根据指定的条件获取数据库记录数");
        } else if ("deleteByExample".equals(methodName)) {
            sb.append(" 根据指定的条件删除数据库符合条件的记录");
        } else if ("deleteByPrimaryKey".equals(methodName)) {
            sb.append(" 根据主键删除数据库的记录");
        } else if ("insert".equals(methodName)) {
            sb.append(" 新写入数据库记录");
        } else if ("insertSelective".equals(methodName)) {
            sb.append(" 动态字段,写入数据库记录");
        } else if ("selectByExample".equals(methodName)) {
            sb.append(" 根据指定的条件查询符合条件的数据库记录");
        } else if ("selectByPrimaryKey".equals(methodName)) {
            sb.append(" 根据指定主键获取一条数据库记录");
        } else if ("updateByExampleSelective".equals(methodName)) {
            sb.append(" 动态根据指定的条件来更新符合条件的数据库记录");
        } else if ("updateByExample".equals(methodName)) {
            sb.append(" 根据指定的条件来更新符合条件的数据库记录");
        } else if ("updateByPrimaryKeySelective".equals(methodName)) {
            sb.append(" 动态字段,根据主键来更新符合条件的数据库记录");
        } else if ("updateByPrimaryKey".equals(methodName)) {
            sb.append(" 根据主键来更新符合条件的数据库记录");
        } else if ("or".equals(methodName)) {
            if (parameterList.isEmpty()) {
                sb.append(" 创建一个新的或者查询条件");
            } else {
                sb.append(" 增加或者的查询条件,用于构建或者查询");
            }
        }
        // sb.append(",");
        // sb.append(introspectedTable.getFullyQualifiedTable());
        method.addJavaDocLine(sb.toString());

        String paramterName;
        for (Parameter parameter : parameterList) {
            sb.setLength(0);
            sb.append(" * @param ");
            paramterName = parameter.getName();
            sb.append(paramterName);
            if ("orderByClause".equals(paramterName)) {
                sb.append(" 排序字段");
            } else if ("distinct".equals(paramterName)) {
                sb.append(" 是否过滤重复数据");
            } else if ("criteria".equals(paramterName)) {
                sb.append(" 过滤条件实例");
            }
            method.addJavaDocLine(sb.toString());
        }
        method.addJavaDocLine(" */");
    }

    @Override
    public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        // sb.append(" * ");
        // sb.append(introspectedColumn.getRemarks());
        // method.addJavaDocLine(sb.toString().replace("\n", " "));
        // sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        method.addJavaDocLine(" */");
    }

    @Override
    public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        // sb.append(" * ");
        // sb.append(introspectedColumn.getRemarks());
        // method.addJavaDocLine(sb.toString().replace("\n", " "));
        Parameter parm = method.getParameters().get(0);
        // sb.setLength(0);
        sb.append(" * @param ");
        sb.append(parm.getName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        method.addJavaDocLine(" */");
    }

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        sb.append(" ");
        sb.append(currentDateStr);
        innerClass.addJavaDocLine(" */");
    }

    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        topLevelClass.addJavaDocLine("/**");
        topLevelClass.addJavaDocLine(" * " + introspectedTable.getRemarks());
        topLevelClass.addJavaDocLine(" * 数据库表:" + introspectedTable.getFullyQualifiedTable());
        if (!suppressDate) {
            topLevelClass.addJavaDocLine(" * @date " + getDateString());
        }
        topLevelClass.addJavaDocLine(" * @author Mybatis Generator");
        topLevelClass.addJavaDocLine(" */");
    }
}

/**
* Xml生成插件,XML重新生成时覆盖历史生成的文件
* @author
* @version 1.0.0
*/
public class XmloverridePluginAdapter extends PluginAdapter {

@Override
public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
    sqlMap.setMergeable(false);
    return super.sqlMapGenerated(sqlMap, introspectedTable);
}

@Override
public boolean validate(List list) {
    return true;
}
}

在test 的resources下面创建
generatorConfig-canyin.xml 这个名字要与(MybatisGeneratorCodeTest 类中读取的xml文件名称一致)

    



    
    
    
        
    
    
    
    

    
        
        
        
    

    
        
        
        
    

    
        
    

    
    
        
        
    
    
    
        
    
    
        
    
    
    
        
    
..........

然后在java resources下面创建一个mgb-jdbc.properties

        jdbc.driverClass=com.mysql.jdbc.Driver
        jdbc.url=jdbc:mysql://自己的id:3306/自己的数据库名称?useUnicode=true&characterEncoding=UTF8&rewriteBatchedStatements=TRUE
        jdbc.userId=自己的账号
        jdbc.password=自己的密码

最后执行MybatisGeneratorCodeTest 进行创建。

因为添加了mapper.xml配置 springboot 项目使用的时候注意扫描包:
Applicaiton.yml 配置

mybatis配置文件扫描

mybatis.mapper-locations: ‘classpath:/com/ziku/msp/canyin/**/*Mapper.xml’

自动识别对应方言的分页

pagehelper.auto-runtime-dialect: true

分页插件很好使用的,添加完依赖后,然后记住一句话就ok 在需要分页的结果前面加上
PageHelper.startPage(pageNum, pageSize);
pageNum: 当前页数
pageSize: 每页条数
具体api参考 官方文档。

      平时项目中使用的,记录一下以便以后使用。

你可能感兴趣的:(java框架)