mybatis + postgresql10 inserted back to the main key ID

If you use useGeneratedKeys MyBatis to generate an auto-increment will result in unsuccessful because the official support only these databases: the mybatis generatedkeys , so if you use on the oracle and postgresql, it is necessary to know their auto-increment is done through the sequence, Therefore, according to this line of thought can be called at the time of insertion sequence to get the next value, and then insert, sequence of questions will not have concurrency problems, because each operation must be in the same session, each session calling sequence is isolated . It can be invoked by the sequence selectKey.

The first:

long saveJob(ScheduleJobDto scheduleJob);

<insert id="saveJob" parameterType="com.common.model.schedule.ScheduleJobDto">
<selectKey resultType="java.lang.Long" order="BEFORE" keyProperty="id" >
select nextval('schedule_job_job_id_seq'::regclass) as id
</selectKey>
insert into schedule_job (id,job_group, bean_name, params, cron_expression, run_status, job_status, job_data, description, revision, create_by, create_time, update_by, update_time, remark, del_flag) values
(#{id}, #{jobGroup}, #{beanName}, #{params}, #{cronExpression}, #{runStatus}, #{jobStatus}, #{jobData}, #{description}, #{revision}, #{createBy}, #{createTime}, #{updateBy}, #{updateTime}, #{remark}, #{delFlag})
</insert>

The second:

long saveJob(ScheduleJobDto scheduleJob);

<insert id="saveJob" parameterType="com.common.model.schedule.ScheduleJobDto">
        <selectKey resultType="java.lang.Long"  order="AFTER" keyProperty="id" >
            select currval('schedule_job_job_id_seq'::regclass) as id
        </selectKey>
        insert into schedule_job (job_group, bean_name, params, cron_expression, run_status, job_status, job_data, description, revision, create_by, create_time, update_by, update_time, remark, del_flag) values
        (#{jobGroup}, #{beanName}, #{params}, #{cronExpression}, #{runStatus}, #{jobStatus}, #{jobData}, #{description}, #{revision}, #{createBy}, #{createTime}, #{updateBy}, #{updateTime}, #{remark}, #{delFlag})
</insert>

Difference: the difference is that the first and second and AFTER BEFORE, AFTER represents after running, obtaining just a sequence of values, the BEFORE retrieves the next value of the sequence prior to insertion of insertion and then, to be noted that corresponds AFTER It is currval, BEFORE corresponds nextval. Also note that, do not use the Java method @Param arguments, it need only be written to the specified list parameterType Mapper, a fact not difficult to find, selectKey of keyProperty is the corresponding Java class field.

Other methods:

1, through select tag + returning keyword insertion do

2, by the select tag

But these methods must correspond in the return value, and can not influence the number of rows back.

Guess you like

Origin www.cnblogs.com/EasonJim/p/10993476.html