mybatis inserts data into mysql and returns the primary key

Function description: The mysql primary key id is incremented automatically, and the corresponding field value is inserted into the returned object


The table design is as follows:

DROP TABLE IF EXISTS `api_quartz`;
CREATE TABLE `api_quartz` (
  `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `job_class_name` varchar(100) DEFAULT NULL COMMENT '需要执行定时任务的类的全路径(包名和类名)',
  `job_group_name` varchar(40) DEFAULT NULL COMMENT 'job的分组名',
  `job_cron` varchar(40) DEFAULT NULL COMMENT '定时任务的时间间隔,可参考http://cron.qqe2.com/',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

The xml of mybatis is as follows:

<insert id="insertAndGetId" parameterType="ApiQuartz" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
    insert into api_quartz (job_class_name, job_group_name,
      job_name,job_cron)
    values (#{jobClassName,jdbcType=VARCHAR}, #{jobGroupName,jdbcType=VARCHAR},
      #{jobName,jdbcType=VARCHAR},#{jobCron,jdbcType=VARCHAR})
  </insert>

The corresponding interface is as follows:

 /**
 * 返回插入数据的主键id值
 * @param apiQuartz
 * @return
 */
int insertAndGetId(ApiQuartz apiQuartz);

The return value of this interface is 1 or 0, representing the success or failure of the insertion respectively (note: it does not represent the returned primary key id value). In this apiQuartzobject , the original apiQuartz.getIdis null, now, assign the primary key id value inserted into the database to it, eg: apiQuartz.getIdyes7

The entity class is as follows:

import lombok.Data;
import java.io.Serializable;

/**
 * 实体类 对应 api_quartz 表,定时任务配置
 */
@Data
public class ApiQuartz implements Serializable {

    private static final long serialVersionUID = 7485426523275431367L;

    /**
     * 主键
     */
    private Long id;

    /**
     * 需要执行定时任务的类的全路径(包名和类名)
     */
    private String jobClassName;

    /**
     * 'job的分组名'
     */
    private String jobGroupName;

    /**
     * '定时任务的时间间隔,可参考http://blog.csdn.net/yansong_8686/article/details/46991189'
     */
    private String jobCron;
}

explain:

  • useGeneratedKeys="true" means to set auto-increment for the primary key

  • keyProperty="userId" means assign the self-incremented Id to the userId field in the entity class.

  • parameterType="com.chenzhou.mybatis.User" This attribute points to the passed parameter entity class

  • As a reminder, there is no resultType attribute in <insert></insert>, so don't add it randomly.

  • The uerId in the entity class must have getter() and setter(); methods (it can also be done with the lombok plugin)

Reference link:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325240893&siteId=291194637