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