【Video & Communication Platform】
http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share
http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share
https://gitee.com/happyangellxq520/spring-boot
à Spring Boot communication platform
http://412887952-qq-com.iteye.com/blog/2321532
Origin of need :
In the last article, we have integrated MyBatic and completed the action of saving the data, but now if you look carefully, the browser will see id=0 in the data . Some people say: I don't need to return the id , I can't use the id return, if the return is 0 , it doesn't matter. But in actual projects, we have many scenarios that need to use the returned id . Netizens have doubts, bloggers, you can brag, there are many scenes, how many are there? You say two to listen.
Usage scenarios - usage scenarios where the id is returned when saving :
Since netizens want bloggers to answer two, let’s answer two:
( 1 ) Scenario 1 : When developing the app , we have the function of leaving a message in the circle of friends. After leaving a message, we want to delete it. At this time, after the request is sent to the background to execute the save() action, we need to return the message. id , otherwise when the App side initiates deletion, it will not know which comment to delete.
( 2 ) Scenario 2 : In the question bank management, we need to enter the question information and the options of the question bank. There can be multiple options for the question bank, as follows:
Question: What is your favorite technology?
A: Java语言 B: PHP语言 C: python语言 D:C语言
那么对于题目信息我们会保存到一张表中Question,对于选项,我们会保存到另外一张表QuestionOption,对于表QuestionOption会有一个外键qid,也就是question的主键。对于Question和QuestionOption的保存是在同一个请求就完成的(如果是题目的保存和选项的保存是两个请求才完成的,那么流程不一样)。在保存QuestionOption的时候,需要用到Question的主键,这时候后台的保存代码是这样的:
Question question = new Question(); int qid = save(Question); QuestionOption qo = new QuestionOption(); qo.setQid(qid); int qid = save(QuestionOption);
这种场景就需要在保存Question的时候,就返回Question的主键了。
类似的场景很多,总之来说,有很多场景需要我们在保存完数据之后就获取到自增主键id。
示例代码:
在上面说了这么多,其实这个很简单,只要在Demo.xml配置下接口,只需要修改下Demo.xml文件:
<insert id="save" parameterType="com.kfit.demo.bean.Demo" useGeneratedKeys="true" keyProperty="id"> insert into demo (name) values (#{name}) </insert>
这时候在访问http://127.0.0.1:8080/save 就可以看到如下的返回信息:
{"id":22,"name":"张三"}
误区1:使用save返回值当做主键id
我们修改下DemoMapper的save返回,增加返回值:
public interface DemoMapper { public int save(Demo demo); }
调用代码:
int rs = demoMapper.save(demo); System.out.println("----->"+rs);
很容易把这里的rs当做返回的是Demo的id,实际含义是:
insert返回的只是insert方法的情况: 1成功 0失败。
视频+交流平台:
http://study.163.com/course/introduction.htm?courseId=1004329008
http://412887952-qq-com.iteye.com/blog/2321532