Auto-generated ID returned in MyBatis

Source: Internet
Author: User

When we insert a piece of data sometimes, because the ID is likely to be generated automatically, what if we want to return this newly inserted ID?

In MySQL data we can add a selectkey under Insert to specify the type and value of the return:method One:<insert id= "AddUser" parametertype= "Com.zhl.pojo.User" > <selectkey resulttype= "Java.lang.Integer" order= "after" keyproperty= "id" > SELECT last_insert_id () as ID</selectKey>INSERT intouserinfo (name, password, age, gender, email)VALUES (#{name:varchar}, #{password:varchar}, #{age:integer},#{gender:integer}, #{email:varchar})</insert>where Resulttype represents the type returned. The ID is the newly inserted ID that is returned.  similar selectkey in Oracle are as follows:<selectkey resulttype= "Java.lang.Integer" order= "before" keyproperty= "id" >SELECT Logs_seq.nextval as ID from DUAL</selectKey>Method Two:<insert id= "AddUser" parametertype= "Com.zhl.pojo.User" usegeneratedkeys= "true" keyproperty= "id" > INSERT INTO UserInfo (name, password, age, gender, email) VALUES (#{name:varchar}, #{password:varchar}, #{age:integer}, #{ge Nder:integer}, #email: VARCHAR}) </insert>view the specific Java code that returns the ID:   public void AddUser () {User.setpassword (User.getname ());   Userserviceimpl userservice = new Userserviceimpl ();   PrintWriter w = null;   try {w = servletactioncontext.getresponse (). Getwriter ();   } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();   }//perform insert operation int count = userservice.adduser (user);   After performing the insert operation, the ID of the user just now has a value of System.out.println ("count=" +count+ "userid=" +user.getid ());   if (count!=0) {w.write ("{\" success\ ": \" Success\ "}");   } else{w.write ("{\" success\ ": \" Fail\ "}"); }} output: Count=1 userid=59

Auto-generated ID returned in MyBatis

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.