欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mybatis generator生成Service,Controller,添加批量新增数据接口(基于mybatis-generator-1.3.5源码修改)

程序员文章站 2023-03-31 19:37:28
好久记录笔记,这段时间做*的项目,数据录入系统基本都是通过excel导入,且数据量大,许多也是单表的录入,这就有很多可以通用的代码,如controller,service层的那一套都是可以代码生成,添加了一个数据库批量添加接口(目前只支持oracle), 代码是基于mybatis-generato ......

    好久记录笔记,这段时间做*的项目,数据录入系统基本都是通过excel导入,且数据量大,许多也是单表的录入,这就有很多可以通用的代码,如controller,service层的那一套都是可以代码生成,添加了一个数据库批量添加接口(目前只支持oracle),

代码是基于mybatis-generator-1.3.5源码修改后的,具体的源码解析,后面等项目上线后,再好好整理一下,这里就粗鲁的记录如何使用。

  mybatis-generator.xml 配置文件

<?xml version="1.0" encoding="utf-8"?>
<!doctype generatorconfiguration
        public "-//mybatis.org//dtd mybatis generator configuration 1.0//en"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorconfiguration>
    <context id="db2tables" targetruntime="mybatis3">
        <!--<plugin type="net.coderbee.mybatis.batch.batchstatementhandler"></plugin>
        <plugin type="net.coderbee.mybatis.batch.batchparameterhandler"></plugin>-->
        <commentgenerator>
            <property name="suppressdate" value="true"/>
            <property name="suppressallcomments" value="true"/>
        </commentgenerator>
        <!--数据库链接地址账号密码-->
        <jdbcconnection driverclass="oracle.jdbc.driver.oracledriver"
                        connectionurl="jdbc:oracle:thin:@127.0.0.1:1521:test"
                        userid="xxxx" password="xxxx" >
            <!--开启读取数据库注释:为了把注释写到相对应的注解里面-->
            <property name="remarksreporting" value="true"></property>
        </jdbcconnection>
        <javatyperesolver>
            <property name="forcebigdecimals" value="false"/>
        </javatyperesolver>
        <!--生成model类存放位置-->
        <javamodelgenerator targetpackage="com.shsoft.platform.domain" targetproject="src/main/java">
            <property name="enablesubpackages" value="true"/>
            <!--设置注解,%s占位符,读取数据库字段注释(多个注解用;分隔),一个占位符读取数据库字段注释,第二数据库字段排序-->
            <property name="annotation" value="@excel(name = &quot;%s&quot;, fixedindex = %s);@apiparam(value = &quot;%s&quot;)"/>
            <!--设置注解需要的包路径,多个用,分隔-->
            <property name="annotationtargetpackage" value="cn.afterturn.easypoi.excel.annotation.excel,io.swagger.annotations.apiparam"/>
        </javamodelgenerator>
        <!--生成映射文件存放位置-->
        <sqlmapgenerator targetpackage="com.shsoft.platform.dao.mapper" targetproject="src/main/java">
            <property name="enablesubpackages" value="true"/>
        </sqlmapgenerator>
        <!--生成dao类存放位置-->
        <javaclientgenerator type="xmlmapper" targetpackage="com.shsoft.platform.dao" targetproject="src/main/java">
            <property name="enablesubpackages" value="true"/>
        </javaclientgenerator>

        <!--生成service,serviceimpl-->
        <javaservicegenerator targetpackage="com.shsoft.platform.service" targetproject="src/main/java"
                              implementationpackage="com.shsoft.platform.service">
        </javaservicegenerator>
        
        <!--生成controller-->
        <javacontrollergenerator targetpackage="com.shsoft.platform.ctrl" targetproject="src/main/java">
            <property name="superclass" value="com.shsoft.platform.ctrl.basecontroller"></property>
        </javacontrollergenerator>

        <!--生成对应表及类名,添加:enableinsertbatch(是否生成批量添加语句,目前只支持oracle),enableinsertbatchignore:批量添加语句中忽略的字段-->
        <table tablename="system_notice" domainobjectname="systemnotice" enablecountbyexample="true" enableupdatebyexample="true"
               enabledeletebyexample="true" enableselectbyexample="true" selectbyexamplequeryid="false" enableinsertbatch="true"
               enablelistparam="true">
            <property name="enableinsertbatchignore" value="createdt"></property>
        </table>
    </context>
</generatorconfiguration>

执行生成代码

最后生成 insertbatch

<insert id="insertbatch" parametertype="java.util.list">
    insert into fixed_assets_indicator (id, order_mark, count_time, 
      city, city_code, fixed_investment_total, 
      fixed_investment_speed_up, folk_investment_total, 
      folk_investment_speed_up, realty_investment_total, 
      realty_investment_speed_up, employment_investment_total, 
      employment_investment_speed_up, technology_investment_total, 
      technology_investment_speed_up, infrastructure_total, 
      infrastructure_speed_up, high_tech_total, 
      high_tech_speed_up, manufacturing_total, 
      manufacturing_speed_up)
    <foreach close=")" collection="list" item="item" open="(" separator="union">
      select #{item.id,jdbctype=varchar}, #{item.ordermark,jdbctype=decimal}, #{item.counttime,jdbctype=timestamp}, 
        #{item.city,jdbctype=varchar}, #{item.citycode,jdbctype=varchar}, #{item.fixedinvestmenttotal,jdbctype=decimal}, 
        #{item.fixedinvestmentspeedup,jdbctype=float}, #{item.folkinvestmenttotal,jdbctype=decimal}, 
        #{item.folkinvestmentspeedup,jdbctype=float}, #{item.realtyinvestmenttotal,jdbctype=decimal}, 
        #{item.realtyinvestmentspeedup,jdbctype=float}, #{item.employmentinvestmenttotal,jdbctype=decimal}, 
        #{item.employmentinvestmentspeedup,jdbctype=float}, #{item.technologyinvestmenttotal,jdbctype=decimal}, 
        #{item.technologyinvestmentspeedup,jdbctype=float}, #{item.infrastructuretotal,jdbctype=decimal}, 
        #{item.infrastructurespeedup,jdbctype=float}, #{item.hightechtotal,jdbctype=decimal}, 
        #{item.hightechspeedup,jdbctype=float}, #{item.manufacturingtotal,jdbctype=decimal}, 
        #{item.manufacturingspeedup,jdbctype=float} from dual
    </foreach>
  </insert>

 

生成service

public class fixedassetsindicatorserviceimpl implements fixedassetsindicatorservice {
    @autowired
    private fixedassetsindicatormapper fixedassetsindicatormapper;

    public int insertbatch(list<fixedassetsindicator> list) {
        if(list != null && list.size() > 0 ){
            fixedassetsindicatorexample fixedassetsindicatorexample = new fixedassetsindicatorexample();
            fixedassetsindicatorexample.createcriteria().andcounttimeequalto(list.get(0).getcounttime());
            fixedassetsindicatormapper.deletebyexample(fixedassetsindicatorexample);
            return fixedassetsindicatormapper.insertbatch(list);
        }
        return 0;
    }
    public pageinfo<fixedassetsindicator> list(listfixedassetsindicatorparam param) {
        fixedassetsindicatorexample example = new fixedassetsindicatorexample();
        if(param.getcounttime() != null){
            example.createcriteria().andcounttimeequalto(param.getcounttime());
        }
        pagehelper.startpage(param.getpagenum(), param.getpagesize());
        example.setorderbyclause("order_mark");
        list<fixedassetsindicator> fromdb = fixedassetsindicatormapper.selectbyexample(example);
        pageinfo pageinfo = new pageinfo(fromdb);
        return pageinfo;
    }

    public fixedassetsindicator get(string id) {
        return fixedassetsindicatormapper.selectbyprimarykey(id);
    }

    public void save(fixedassetsindicator todb) {
        fixedassetsindicatormapper.insertselective(todb);
    }

    public void delete(string id) {
        fixedassetsindicatormapper.deletebyprimarykey(id);
    }

    public void update(fixedassetsindicator todb) {
        fixedassetsindicatormapper.updatebyprimarykeyselective(todb);
    }
}

 

生成controller:添加excel导入导出接口(基于easypoi导入导出)

@slf4j
@controller
@requestmapping("/fixedassetsindicator")
@api(description = "能源投资统计科:分市固定资产投资主要指标")
public class fixedassetsindicatorcontroller extends basecontroller {

    @autowired
    private fixedassetsindicatorservice fixedassetsindicatorservice;

    @apioperation(value = "列表查询", httpmethod = "post")
    @requestmapping("/list.do")
    @responsebody
    public jsonresult list(@validated listfixedassetsindicatorparam param) throws shsoftexception {
        jsonresult result = new jsonresult(fixedassetsindicatorservice.list(param));
        return result;
    }

    @apioperation(value = "单条查询", httpmethod = "post")
    @requestmapping("/get.do")
    @responsebody
    public jsonresult get(string id) throws shsoftexception {
        jsonresult result = new jsonresult(fixedassetsindicatorservice.get(id));
        return result;
    }

    @apioperation(value = "删除", httpmethod = "post")
    @requestmapping("/delete.do")
    @responsebody
    public jsonresult delete(string id) throws shsoftexception {
        fixedassetsindicatorservice.delete(id);
        return new jsonresult();
    }

    @apioperation(value = "新增", httpmethod = "post")
    @requestmapping("/save.do")
    @responsebody
    public jsonresult save(@validated fixedassetsindicator todb) throws shsoftexception {
        todb.setid(new uuidfactory().generate().tostring());
        fixedassetsindicatorservice.save(todb);
        return new jsonresult();
    }

    @apioperation(value = "修改", httpmethod = "post")
    @requestmapping("/update.do")
    @responsebody
    public jsonresult update(@validated fixedassetsindicator todb) throws shsoftexception {
        fixedassetsindicatorservice.update(todb);
        return new jsonresult();
    }


    @apioperation(value = "导出", httpmethod = "post")
    @requestmapping("/export.do")
    @responsebody
    public jsonresult exportexcel(@validated listfixedassetsindicatorparam param, httpservletrequest request, httpservletresponse response) throws shsoftexception {
        jsonresult result = new jsonresult();
        pageinfo<fixedassetsindicator> pageinfo = fixedassetsindicatorservice.list(param);
        list<fixedassetsindicator> list = pageinfo.getlist();
        list<map<string, object>> listmap = new arraylist<map<string, object>>();
        if(list != null && list.size() > 0){
            for (int i = 0; i < list.size(); i++) {
                map<string, object> lm = new hashmap<string, object>();
                if(list.get(i).getcity() != null ){
                    lm.put("city", list.get(i).getcity());
                }
                if(list.get(i).getcitycode() != null ){
                    lm.put("citycode", list.get(i).getcitycode());
                }
                if(list.get(i).getfixedinvestmenttotal() != null ){
                    lm.put("fixedinvestmenttotal", list.get(i).getfixedinvestmenttotal());
                }
                if(list.get(i).getfixedinvestmentspeedup() != null ){
                    lm.put("fixedinvestmentspeedup", list.get(i).getfixedinvestmentspeedup());
                }

                if(list.get(i).getfolkinvestmenttotal() != null ){
                    lm.put("folkinvestmenttotal", list.get(i).getfolkinvestmenttotal());
                }
                if(list.get(i).getfolkinvestmentspeedup() != null ){
                    lm.put("folkinvestmentspeedup", list.get(i).getfolkinvestmentspeedup());
                }
                listmap.add(lm);
            }
        }
        calendar calendar = calendar.getinstance();
        calendar.settime(param.getcounttime());
        map<string, object> map = new hashmap<string, object>();
        map.put("maplist", listmap);
        map.put("year", calendar.get(calendar.year));
        map.put("month", calendar.get(calendar.month + 1));
        templateexportparams params = new templateexportparams("excel_temple/固定资产投资/分市固定资产投资主要指标.xls");
        workbook workbook = excelexportutil.exportexcel(params, map);
        outputstream os = null;
        try {
            response.setheader("content-type", "application/vnd.ms-excel;charset=utf-8");
            response.setheader("content-disposition","attachment;filename=分市固定资产投资主要指标.xls");
            os = response.getoutputstream();
            workbook.write(os);
            os.flush();
        } catch (exception e) {
            e.printstacktrace();
        }
        return result;
    }


    @apioperation(value = "导入", httpmethod = "post")
    @requestmapping("/import.do")
    @responsebody
    public jsonresult importexcel(httpservletrequest request) throws shsoftexception {
        multiparthttpservletrequest multiparthttpservletrequest = ((multiparthttpservletrequest) request);
        multipartfile file = multiparthttpservletrequest.getfile("file");
        jsonresult result = new jsonresult();
        importparams params = new importparams();
        params.settitlerows(3);
        params.setheadrows(1);
        params.setstartrows(1);
        try {
            if(file.getsize() > 0){
                list<fixedassetsindicator> datalist = new shexcelimportutils().importexcelbyis(file.getinputstream(), fixedassetsindicator.class,
                        params, false).getlist();
                fixedassetsindicatorservice.insertbatch(datalist);
            }else{
                result = new jsonresult(new errormessage(error.dampe_field_unauth.getcode(),error.dampe_field_unauth.getmessage()));
            }
        } catch (exception e) {
            throw new shsoftexception(e.getmessage(),e);
        }
        return result;
    }




}

 若文章在表述和代码方面如有不妥之处,欢迎批评指正。留下你的脚印,欢迎评论!希望能互相学习。需要源码和jar包的留下邮箱