Foreword
Although mybatis already have code generation, but for SpringBoot projects generated or needs to be changed, but did not have a logical layer and control layer. But these things can not escape, so I for a single table, made a code generator.
mybatis-dsc-generator
根据完善的数据库表结构,一键生成dao.java,mapper.xml,service.java,serviceImpl.java,controller.java,完成单表的增删改查、组合条件集合查询,组合条件分页查询。
Source Address
- GitHub:https://github.com/flying-cattle/mybatis-dsc-generator
- Cloud code: https://gitee.com/flying-cattle/mybatis-dsc-generator
MAVEN address
<dependency> <groupId>com.github.flying-cattle</groupId> <artifactId>mybatis-dsc-generator</artifactId> <version>1.0.0.RELEASE</version> </dependency>
Data table structure style
TABLE `order` the CREATE ( ` id` BIGINT (20 is) the AUTO_INCREMENT the COMMENT the NOT NULL 'ID', `order_no` VARCHAR (50) the COMMENT the NOT NULL 'Order Number', ` uid` BIGINT (20 is) the COMMENT the NOT NULL 'User ID' , `source` VARCHAR (50) the COMMENT the NOT NULL 'source', ` product_id` BIGINT (20 is) the COMMENT the NOT NULL 'item ID', `product_name` VARCHAR (100) the NOT NULL the COMMENT 'product name', ` unit_price` int ( 10) unsigned NOT NULL COMMENT 'monovalent', `number` int (10) unsigned NOT NULL COMMENT 'number', ` selling_price` int (. 11) the COMMENT the DEFAULT NULL 'selling price', `state` int (10) unsigned the NOT NULL DEFAULT '0' COMMENT '0 waiting for payment, a successful payment, payment fails 2, 3 revocation', `create_time` timestamp the NOT NULL the DEFAULT CURRENT_TIMESTAMP the COMMENT 'Created ' `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT ' changes over time transactions', a PRIMARY KEY (` id`) ) = the InnoDB ENGINE the AUTO_INCREMENT the DEFAULT = 2 the CHARSET = utf8mb4 the COMMENT = 'order information';
Notes requires the existence of the table, as required must have a primary key id, cut into bigint, all columns must Notes (Notes facilitates generating java).
Generating entity classes
The method of generating the reference source in: https://github.com/flying-cattle/mybatis-dsc-generator/blob/master/src/main/java/com/github/mybatis/test/TestMain.java
Generating entity classes
/** * @filename:Order 2018年7月5日 * @project deal-center V1.0 * Copyright(c) 2018 BianP Co. Ltd. * All right reserved. */ package com.xin.dealcenter.entity; import java.io.Serializable; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.ToString; import lombok.NoArgsConstructor; import lombok.AllArgsConstructor; /** * * @Description: 订单 * @Author: BianP * @CreateDate: 2018年7月5日 * @Version: V1.0 * */ @Data @ToString @AllArgsConstructor @NoArgsConstructor public class Order implements Serializable { private static final long serialVersionUID = 1531104207412L; @ApiModelProperty(name = "id" , value = "ID") private Long id; @ApiModelProperty(name = "orderNo" , value = "订单编号") private String orderNo; @ApiModelProperty(name = "uid" , value = "用户ID") private Long uid; @ApiModelProperty(name = "source" , value = "来源") private String source; @ApiModelProperty(name = "productId" , value = "产品ID") private Long productId; @ApiModelProperty(name = "productName ", value =" Product name ") Private String productName; @ApiModelProperty(name = "unitPrice" , value = "单价") private Integer unitPrice; @ApiModelProperty(name = "number" , value = "数量") private Integer number; @ApiModelProperty(name = "sellingPrice" , value = "卖价") private Integer sellingPrice; @ApiModelProperty(name = "state" , value = "0等待支付,1支付成功,2支付失败,3撤销") private Integer state; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") @ApiModelProperty(name = "createTime" , value = "创建时间") private Date createTime; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", TimeZone = "GMT + 8") @ApiModelProperty (name = "updateTime", value = "transaction changes over time") private Date updateTime; }
Generated DAO
/** * @filename:OrderDao 2018年7月5日 * @project deal-center V1.0 * Copyright(c) 2018 BianP Co. Ltd. * All right reserved. */ package com.xin.dealcenter.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.xin.dealcenter.entity.Order; /** * * @Description: 订单——DAO * @Author: BianP * @CreateDate: 2018年7月5日 * @Version: V1.0 * */ @Mapper public interface OrderDao { public Order selectByPrimaryKey(Long id); public int deleteByPrimaryKey(Long id); public int insertSelective(Order order); public int updateByPrimaryKeySelective(Order order); public List<Order> queryOrderList(Order order); }
The resulting 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.xin.dealcenter.dao.OrderDao"> <resultMap id="BaseResultMap" type="com.xin.dealcenter.entity.Order"> <id column="id" jdbcType="BIGINT" property="id" /> <id column="order_no" jdbcType="VARCHAR" property="orderNo" /> <id column="uid" jdbcType="BIGINT" property="uid" /> <id column="source" jdbcType="VARCHAR" property="source" /> <id column="product_id" jdbcType="BIGINT" property="productId" /> <id column="product_name" jdbcType="VARCHAR" property="productName" /> <id column="unit_price" jdbcType="INTEGER" property="unitPrice" /> <id column="number" jdbcType="INTEGER" property="number" /> <id column="selling_price" jdbcType="INTEGER" property="sellingPrice" /> <id column="state" jdbcType="INTEGER" property="state" /> <id column="create_time" jdbcType="TIMESTAMP" property="createTime" /> <id column="update_time" jdbcType="TIMESTAMP" property="updateTime" /> </resultMap> <sql id="Base_Column_List"> id, order_no, uid, source, product_id, product_name, unit_price, number, selling_price, state, create_time, update_time </sql> <!-- 查询 --> <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from order where id = #{id,jdbcType=BIGINT} </select> <!-- 删除 --> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long"> delete from order where id = #{id,jdbcType=BIGINT} </delete> <!-- 选择添加 --> <insert id="insertSelective" parameterType="com.xin.dealcenter.entity.Order"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long"> SELECT LAST_INSERT_ID() </selectKey> insert into order <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="orderNo != null"> order_no, </if> <if test="uid != null"> uid, </if> <if test="source != null"> source, </if> <if test="productId != null"> product_id, </if> <if test="productName != null"> product_name, </if> <if test="unitPrice != null"> unit_price, </if> <if test="number != null"> number, </if> <if test="sellingPrice != null"> selling_price, </if> <if test="state != null"> state, </if> <if test="createTime != null"> create_time, </if> <if test="updateTime != null"> update_time, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=BIGINT}, </if> <if test="orderNo != null"> #{orderNo,jdbcType=VARCHAR}, </if> <if test="uid != null"> #{uid,jdbcType=BIGINT}, </if> <if test="source != null"> #{source,jdbcType=VARCHAR}, </if> <if test="productId != null"> #{productId,jdbcType=BIGINT}, </if> <if test="productName != null"> #{productName,jdbcType=VARCHAR}, </if> <if test="unitPrice != null"> #{unitPrice,jdbcType=INTEGER}, </if> <if test="number != null"> #{number,jdbcType=INTEGER}, </if> <if test="sellingPrice != null"> #{sellingPrice,jdbcType=INTEGER}, </if> <if test="state != null"> #{state,jdbcType=INTEGER}, </if> <if test="createTime != null"> #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null"> #{updateTime,jdbcType=TIMESTAMP}, </if> </trim> </insert> <!-- 选择修改 --> <update id="updateByPrimaryKeySelective" parameterType="com.xin.dealcenter.entity.Order"> update order <set> <if test="id != null"> id = #{id,jdbcType=BIGINT}, </if> <if test="orderNo != null"> order_no = #{orderNo,jdbcType=VARCHAR}, </if> <if test="uid != null"> uid = #{uid,jdbcType=BIGINT}, </if> <if test="source != null"> source = #{source,jdbcType=VARCHAR}, </if> <if test="productId != null"> product_id = #{productId,jdbcType=BIGINT}, </if> <if test="productName != null"> product_name = #{productName,jdbcType=VARCHAR}, </if> <if test="unitPrice != null"> unit_price = #{unitPrice,jdbcType=INTEGER}, </if> <if test="number != null"> number = #{number,jdbcType=INTEGER}, </if> <if test="sellingPrice != null"> selling_price = #{sellingPrice,jdbcType=INTEGER}, </if> <if test="state != null"> state = #{state,jdbcType=INTEGER}, </if> <if test="createTime != null"> create_time = #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null"> update_time = #{updateTime,jdbcType=TIMESTAMP}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> <!-- 组合条件查询 --> <select id="queryOrderList" parameterType="com.xin.dealcenter.entity.Order" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from order <where> <if test="id != null"> id = #{id,jdbcType=BIGINT} </if> <if test="orderNo != null"> AND order_no = #{orderNo ,jdbcType=VARCHAR} </if> <if test="uid != null"> AND uid = #{uid ,jdbcType=BIGINT} </if> <if test="source != null"> AND source = #{source ,jdbcType=VARCHAR} </if> <if test="productId != null"> AND product_id = #{productId ,jdbcType=BIGINT} </if> <if test="productName != null"> AND product_name = #{productName ,jdbcType=VARCHAR} </if> <if test="unitPrice != null"> AND unit_price = #{unitPrice ,jdbcType=INTEGER} </if> <if test="number != null"> AND number = #{number ,jdbcType=INTEGER} </if> <if test="sellingPrice != null"> AND selling_price = #{sellingPrice ,jdbcType=INTEGER} </if> <if test="state != null"> AND state = #{state ,jdbcType=INTEGER} </if> <if test="createTime != null"> AND create_time = #{createTime ,jdbcType=TIMESTAMP} </if> <if test="updateTime != null"> AND update_time = #{updateTime ,jdbcType=TIMESTAMP} </if> </where> </select> </mapper>
Resulting SERVICE
/ ** * @filename: OrderService 2018 Nian 7 Yue 5 Ri * @project Deal-Center V1.0 * Copyright (c) 2018 BianP Co. Ltd. * All right Reserved. * / Package Penalty for com.xin.dealcenter.service; java.util.List Import; Import com.github.pagehelper.PageInfo; Import com.item.util.AppPage; Import com.xin.dealcenter.entity.Order; / ** * * @Description: Order --service * @ author: BianP * @CreateDate: 2018 Nian 7 Yue 5 Ri * @Version: V1.0 * * / public interface OrderService { / ** * @explain query order object * @param object parameter: the above mentioned id * @return the Order * @author BianP * / public selectByPrimaryKey the Order (Long the above mentioned id); / ** * @explain delete the order object * @param object parameter: the above mentioned id * @return int * @author BianP * / public int deleteByPrimaryKey (Long the above mentioned id); / * * * @explain add order object * @param object parameter: the Order * @return int * @author BianP * / public int insertSelective (the Order the Order); / ** * @explain modify the order object * @param object parameter: the Order * @ int return * @author BianP * / public int updateByPrimaryKeySelective (the Order the Order); / ** * @explain collection of orders inquiry * @Param object parameters: the Order * @return List <the Order> * @author BianP * / public List <the Order> queryOrderList (the Order the Order); / ** * @explain paging query orders * @param object parameters: the Order * @return PageInfo <the Order> * @author BianP * / public PageInfo <the Order> getOrderBySearch (AppPage <the Order> Page); }
Generated SERVICE_IMPL
/** * @filename:OrderServiceImpl 2018年7月5日 * @project deal-center V1.0 * Copyright(c) 2018 BianP Co. Ltd. * All right reserved. */ package com.xin.dealcenter.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.item.util.AppPage; import com.xin.dealcenter.entity.Order; import com.xin.dealcenter.dao.OrderDao; import com.xin.dealcenter.service.OrderService; /** * * @Description: 订单——SERVICEIMPL @Author *: BianP * @CreateDate: 2018 Nian 7 Yue 5 Ri * @Version: V1.0 * * / @Service public class OrderServiceImpl the implements OrderService { @Autowired public OrderDao OrderDao; // query object @Override public the Order selectByPrimaryKey (Long ID) { return orderDao.selectByPrimaryKey (ID); } // remove objects @Override public int deleteByPrimaryKey (Long ID) { return orderDao.deleteByPrimaryKey (ID); } // add objects @Override public int insertSelective (the Order Order) { return orderDao.insertSelective (Order); } // modify Object @Override public int updateByPrimaryKeySelective(Order order) { return orderDao.updateByPrimaryKeySelective(order); } //查询集合 @Override public List<Order> queryOrderList(Order order) { return orderDao.queryOrderList(order); } //分页查询 @Override public PageInfo<Order> getOrderBySearch(AppPage<Order> page) { // TODO Auto-generated method stub PageHelper.startPage(page.getPageNum(),page.getPageSize()); List<Order> list=orderDao.queryOrderList(page.getParam()); PageInfo<Order> pageInfo = new PageInfo<Order>(list); return pageInfo; } }
Generated CONTROLLER
/** * @filename:OrderController 2018年7月5日 * @project deal-center V1.0 * Copyright(c) 2018 BianP Co. Ltd. * All right reserved. */ package com.xin.dealcenter.webApi; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.github.pagehelper.PageInfo; import com.item.util.AppPage; import com.item.util.JsonResult; import com.xin.dealcenter.entity.Order; import com.xin.dealcenter.service.OrderService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; /** * * @Description: 订单接口层 * @Author: BianP * @CreateDate: 2018年7月5日 * @Version: V1.0 * */ @Api(description = "订单",value="订单" ) @RestController @RequestMapping("/order") OrderController {class public Logger Logger = LoggerFactory.getLogger (this.getClass ()); @Autowired public OrderService the OrderServiceImpl; / ** * @explain order object query <swagger GET request> * @param Object Parameters: ID * @return Order * BianP @author * @time 2018 Nian 7 Yue 5 Ri * / @GetMapping ( "/ getOrderById / {the above mentioned id}") @ApiOperation (value = "get order information", notes = "get order information [order], author: BianP ") @ApiImplicitParam (paramType =" path ", name =" ID ", value =" Order ID ", required = to true, dataType =" Long ") public a JsonResult getOrderById (@PathVariable (" ID ") Long ID) { a JsonResult result = new JsonResult (); try { the Order Order = the OrderServiceImpl.selectByPrimaryKey(id); if (order!=null) { result.setCode (. 1); result.setMessage ( "Success"); result.setData (Order); } the else { logger.error ( "Get Order Failed ID:" + ID); result.setCode (-1); Result .setMessage ( "Get your order is not present"); } } the catch (exception E) { logger.error ( "Get Order execution exception:" + e.getMessage ()); result.setCode (-1); Result. setMessage ( "abnormality, please try again later"); } return the Result; } / ** * Add @explain order object * @param object parameter: the Order * @return int * @author BianP * @time 2018 Nian 7 Yue 5 * / @PostMapping ( "/insertSelective") @ApiOperation (value = "Add an order", notes = "Add an order [order], author: BianP") a JsonResult insertSelective public (the Order Order) { a JsonResult a JsonResult new new Result = (); the try { int orderServiceImpl.insertSelective RG = (Order); IF (RG> 0) { result.setCode (. 1); result.setMessage ( "Success") ; result.setData (Order); } the else { logger.error ( "Add Order failed:" + order.toString ()); result.setCode (-1); result.setMessage ( "failed. Please try test "); } } the catch (exception E) { logger.error (" Add Order execution exception: "+ e.getMessage ()); result.setCode (-1); result.setMessage (" abnormality, please wait Retry "); } return the Result; } * @explain delete orders objects /** * @param 对象参数:id * @return int * @author BianP * @time 2018年7月5日 */ @PostMapping("/deleteByPrimaryKey") @ApiOperation(value = "删除订单", notes = "删除订单,作者:BianP") @ApiImplicitParam(paramType="query", name = "id", value = "订单id", required = true, dataType = "Long") public JsonResult deleteByPrimaryKey(Long id){ JsonResult result=new JsonResult(); try { int reg=orderServiceImpl.deleteByPrimaryKey(id); if (reg>0) { result.setCode(1); result.setMessage("成功"); result.setData(id); } else { logger.error("Delete order failed ID: "+ the above mentioned id); result.setCode (-1); result.setMessage ( "execution error, please try again later"); } } the catch (Exception E) { logger.error ( "Delete order execution exception:" + e.getMessage ()); result.setCode (-1) ; result.setMessage ( "abnormality, please try again later"); } return the Result; } / ** * @explain modify the order object * @param object parameter: the Order * @return the Order * @author BianP * @time 2018 on July 5 * / @ApiOperation (value = "modify Order", notes = "modify Order [order], author: BianP") @PostMapping ( "/ updateByPrimaryKeySelective") public JsonResult updateByPrimaryKeySelective (the Order the Order) { JsonResult the Result = a JsonResult new new (); the try { orderServiceImpl.updateByPrimaryKeySelective REG = int (Order); IF (REG> 0) { result.setCode (. 1); result.setMessage ( "Success"); result.setData (Order); } the else { logger.error ( "Modify Order failure ID: "+ order.toString ()); result.setCode (-1); result.setMessage (" execution error, please try again later "); } } the catch (Exception E) { logger.error (" modify Order execution exception: "+ e.getMessage ()); result.setCode (-1); result.setMessage (" abnormality, please try again later "); } return Result; } / ** * Get matching @explain orders * @param object parameters: the Order * @return List <the Order> @Author BianP * * @time 2018 Nian 7 Yue 5 Ri * / @ApiOperation (value = "condition check orders", notes = "condition query [order], author: BianP") @PostMapping ( "/ queryOrderList") Public a JsonResult queryOrderList (the Order Order) { a JsonResult a JsonResult new new Result = (); the try { List <the Order> List = orderServiceImpl.queryOrderList (Order); result.setCode (. 1); result.setMessage ( "Success"); Result .setData (List); } the catch (exception E) { logger.error ( "Get Order execution exception:" + e.getMessage ()); result.setCode (-1); result.setMessage ( "abnormality, please wait Retry "); } return Result; } / ** * Order query conditions @explain tab * @param object parameters: AppPage <the Order> * @return PageInfo <the Order> * @author BianP * @time July 5, 2018 day * / @GetMapping ( "/getPageOrder") @ApiOperation (value = "Query Page", notes = "tab query returns the object [PageInfo <Order>], Author: Peng edge") @ApiImplicitParams ({ @ApiImplicitParam (paramType = "Query", name = "pageNum", value = "current page", required = true, dataType = "int") , @ApiImplicitParam (paramType = "Query", name = "pageSize", value = "number of lines page", required = true, dataType = "int") }) public a JsonResult getOrderBySearch (pageNum Integer, Integer the pageSize) { a JsonResult a JsonResult new new Result = (); AppPage <the Order> Page new new AppPage = <the Order> (); page.setPageNum (pageNum); page.setPageSize (the pageSize); / / other parameters of the Order Order the Order new new = (); Page.the setParam (Order); // paged data try { PageInfo <the Order> = orderServiceImpl.getOrderBySearch PageInfo (Page); result.setCode (. 1); result.setMessage ( "Success"); result.setData (PageInfo); } the catch (Exception E) { logger.error ( "paging query Order execution exception: "+ e.getMessage ()); result.setCode (-1); result.setMessage (" abnormality, please try again later "); } return Result; } }
See here, we should be able to see that this code is generated only for specific projects, first springboot, followed mybatis and pagehelper use, and use the swagger and lombok.