PostgreSQL returns primary key when using Mybatis,insert

Source: Internet
Author: User
Tags postgresql

The common INSERT statement in MyBatis is this:

<insert id= "Insert" parametertype= "Com.xxx.xxx.xxDo" >    "table_name" (key, value)    values ( #{key,jdbctype=VARCHAR}, #{value,jdbctype=</insert>

The public integer insert of the DAO interface at this time (Databaseobject do); The returned Integer is the number of rows that were changed, returning 1 when the insert succeeds

The primary key is added by default by the database itself, and can be obtained using the Selectkey subquery statement

However, the sequence name generated by PostgreSQL for the serial field is: Table name _ column name _seq, but this sequence cannot be accessed individually

So this method requires some modification, and here's the easiest way to do it:

Add usegeneratedkeys= "true" keyproperty= "ID " to the INSERT statement

usegeneratedkeys= "true" keyproperty= "id">    "table_name" (key, value)    values (#{key , Jdbctype=varchar}, #{value,jdbctype=</insert>

Usegeneratedkeys let MyBatis to assign primary key Id,keyproperty to specify primary key name when primary key name is not ID

At this point MyBatis will add the assigned primary key to the insert's parameter do, and the primary key can be returned by the getid of do.

Using in the server tier

 Public Integer Insert (Databaseobject xxdo) {
if (Mybatisdao.insert (Xxdo) > 0) { return xxdo. getId (); } Else { return 0; }}

PostgreSQL returns primary key when using Mybatis,insert

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.