SpringBoot入门构建Web应用程序

1.1 技术介绍

Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。

1.2 技术注意点

a.springboot生成环境部署,热部署插件不要使用,去除springs-boot-devtools

b.监控相关的jar包去除,

  1. spring-boot-starter-actuator 的监控
  2. druid 的监控
  3. swagger的接口

c.打包一定要跳过测试test

1.3 技术具体demo文件路径

E:\MyJAVA\SpringMakeup

1.4 demo的UML图

1.5 demo的技术代码实现

pom准备
  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <!-- mybatis -->
  7. <dependency>
  8. <groupId>org.mybatis.spring.boot</groupId>
  9. <artifactId>mybatis-spring-boot-starter</artifactId>
  10. <version>2.0.0</version>
  11. </dependency>
  12. <!-- mysql -->
  13. <dependency>
  14. <groupId>mysql</groupId>
  15. <artifactId>mysql-connector-java</artifactId>
  16. <version>5.1.21</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-test</artifactId>
  21. <scope>test</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>junit</groupId>
  25. <artifactId>junit</artifactId>
  26. <version>4.12</version>
  27. </dependency>
  28. <!--热部署 -->
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-devtools</artifactId>
  32. <optional>true</optional>
  33. </dependency>
  34. <!-- tomcat的支持. -->
  35. <dependency>
  36. <groupId>org.apache.tomcat.embed</groupId>
  37. <artifactId>tomcat-embed-jasper</artifactId>
  38. </dependency>
  39. <!--自动生成bean -->
  40. <dependency>
  41. <groupId>org.mybatis.generator</groupId>
  42. <artifactId>mybatis-generator-core</artifactId>
  43. <version>1.3.6</version>
  44. </dependency>
  45. <!-- 对象转换成json引入如下依赖 -->
  46. <!-- 文档:https://www.yiibai.com/jackson/jackson_first_application.html#article-start -->
  47. <dependency>
  48. <groupId>com.fasterxml.jackson.core</groupId>
  49. <artifactId>jackson-core</artifactId>
  50. <version>2.9.5</version>
  51. </dependency>
  52. <dependency>
  53. <groupId>com.fasterxml.jackson.core</groupId>
  54. <artifactId>jackson-databind</artifactId>
  55. <version>2.9.5</version>
  56. </dependency>
  57. <dependency>
  58. <groupId>com.fasterxml.jackson.core</groupId>
  59. <artifactId>jackson-annotations</artifactId>
  60. <version>2.9.5</version>
  61. </dependency>
  62. <dependency>
  63. <groupId>com.fasterxml.jackson.module</groupId>
  64. <artifactId>jackson-module-jaxb-annotations</artifactId>
  65. <version>2.9.5</version>
  66. </dependency>
  67. </dependencies>
  68. <build>
  69. <plugins>
  70. <plugin>
  71. <groupId>org.springframework.boot</groupId>
  72. <artifactId>spring-boot-maven-plugin</artifactId>
  73. </plugin>
  74. <plugin>
  75. <groupId>org.apache.maven.plugins</groupId>
  76. <artifactId>maven-surefire-plugin</artifactId>
  77. <configuration>
  78. <skip>true</skip>
  79. </configuration>
  80. </plugin>
  81. </plugins>
  82. </build>

vue编写
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>vue增删改查</title>
  6. </head>
  7. <body>
  8. <div id="app1">
  9. <table border="1" cellpadding="0" cellspacing="0">
  10. <tr>
  11. <td colspan="2" align="center">学生基本信息</td>
  12. </tr>
  13. <tr>
  14. <td>姓名</td>
  15. <td>
  16. <input v-model="name" style="width:150px" />
  17. </td>
  18. </tr>
  19. <tr>
  20. <td>性别</td>
  21. <td>
  22. <input type="radio" id="boy" value="男" v-model="sex">
  23. <label for="boy"></label>
  24. <input type="radio" id="girl" value="女" v-model="sex">
  25. <label for="girl"></label>
  26. </td>
  27. </tr>
  28. <tr>
  29. <td>年龄</td>
  30. <td>
  31. <select v-model="age">
  32. <option v-for="option in options" v-bind:value="option.value"
  33. :disabled="option.value==0?true:false" :class="{statusbtn:option.value==0}">
  34. {{ option.text }}
  35. </option>
  36. </select>
  37. </td>
  38. </tr>
  39. <tr>
  40. <td>成绩</td>
  41. <td>
  42. <input v-model.number="score" placeholder="请输入成绩" style="width:150px"/>
  43. </td>
  44. </tr>
  45. <tr>
  46. <td>兴趣</td>
  47. <td>
  48. <span v-for="(studentHobby,index) in studentHobbys" >
  49. <input type="checkbox" name="interests" v-bind:value="index+1" v-model="checkData">
  50. <label>{{ studentHobby.hobby }}</label>
  51. </span>
  52. </td>
  53. </tr>
  54. <tr>
  55. <td colspan="2" align="center">
  56. <input type="submit" :value="form" @click="submission" v-if="isAdd"/>
  57. <input type="submit" :value="form" @click="update" v-else="!isAdd"/>
  58. <input type="submit" id="reset" value="重置" v-on:click="resets"/>
  59. </td>
  60. </tr>
  61. </table>
  62. <br /><br /><br /><br />
  63. <table border="1" cellspacing="0" cellpadding="0" id="listTable">
  64. <tr>
  65. <td>选中</td>
  66. <td>姓名</td>
  67. <td>性别</td>
  68. <td>年龄</td>
  69. <td>成绩</td>
  70. <td>兴趣</td>
  71. <td>操作</td>
  72. </tr>
  73. <tr>
  74. <td>
  75. <label>全选</label>
  76. <input type="checkbox" name="item" v-model='checked' v-on:click='checkedAll'/>
  77. </td>
  78. <td colspan="6" align="center">
  79. <input type="button" value="选中删除" @click="delRow"/>
  80. </td>
  81. </tr>
  82. <tr v-for="(items,index) in student">
  83. <td><input type="checkbox" name="item" v-model="checkList" :value="items.id"/>{{1 + index}}</td>
  84. <td>{{items.name}}</td>
  85. <td>{{items.sex}}</td>
  86. <td>{{items.age}}</td>
  87. <td>{{ items.score }}</td>
  88. <td><span v-for="item in items.hobby">{{item.hobby}} </span></td>
  89. <td>
  90. <input type="button" value="删除" @click="del(items.id)"/>
  91. <input type="button" name="update" value="修改" @click="modify(items)" />
  92. </td>
  93. </tr>
  94. </table>
  95. </div>
  96. <style>
  97. .statusbtn {
  98. color: #d6caca;
  99. cursor: not-allowed; /*这个在button上面才管用,是一个禁用的小标识*/
  100. }
  101. </style>
  102. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  103. <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
  104. <script src="https://cdn.bootcss.com/qs/6.6.0/qs.min.js"></script>
  105. <script>
  106. var app1=new Vue({
  107. el:'#app1',
  108. data:{
  109. options: [
  110. { text: '请选择', value: '0' },
  111. { text: '16', value: '16' },
  112. { text: '17', value: '17' },
  113. { text: '18', value: '18' },
  114. { text: '19', value: '19' },
  115. { text: '20', value: '20' },
  116. { text: '21', value: '21' },
  117. { text: '22', value: '22' },
  118. { text: '23', value: '23' },
  119. ],
  120. id:'',
  121. name:'',
  122. age:'0',
  123. sex:'男',
  124. score:'',
  125. studentHobbys:[],
  126. student:[],
  127. form:'提交',
  128. isAdd: true,
  129. checkData: [],//后台请求的数据
  130. checked:false,//全选框
  131. checkList: []
  132. },
  133. watch: { // 监视双向绑定的数据数组
  134. 'checkList': {
  135. handler(val, oldVal){ // 数据数组有变化将触发此函数
  136. if (val.length === this.student.length) {
  137. this.checked = true;
  138. } else {
  139. this.checked = false;
  140. }
  141. },
  142. deep: true // 深度监视
  143. }
  144. },
  145. created: function (){
  146. this.getStudent();
  147. this.getHobbysAll();
  148. },
  149. methods: {
  150. getHobbysAll: function(){
  151. axios.get('http://localhost:8080/getHobbys')
  152. .then(function (response) {
  153. var arr = response.data;
  154. app1.studentHobbys = arr;
  155. })
  156. .catch(function (error) {
  157. })
  158. },
  159. getStudent:function () {
  160. axios.post('http://localhost:8080/getAll').
  161. then(function (response){
  162. var arr=response.data;
  163. app1.student=arr;
  164. }) .catch(function (error) {
  165. })
  166. },
  167. submission:function () {
  168. // console.log("选中:"+this.checkData);
  169. //获取兴趣
  170. var selectedValue=this.checkData;
  171. axios.get('http://localhost:8080/addStudent?name='+this.name+'&sex='+this.sex+'&age='+
  172. this.age+'&score='+this.score+'&hobbys='+selectedValue)
  173. .then(function (response) {
  174. //更新
  175. app1.getStudent();
  176. //重置
  177. app1.resets();
  178. }).catch(function (error) {
  179. })
  180. },
  181. del:function (e) {
  182. // console.log(e);
  183. axios.get('http://localhost:8080/deleteStudent?studentId='+e)
  184. .then(function (response) {
  185. app1.getStudent();
  186. }).catch(function (error) {
  187. })
  188. },
  189. //选中删除
  190. delRow:function(){
  191. for(var i=0;i<this.checkList.length;i++){
  192. axios.get('http://localhost:8080/deleteStudent?studentId='+this.checkList[i])
  193. .then(function (response) {
  194. app1.getStudent();
  195. }).catch(function (error) {
  196. })
  197. }
  198. },
  199. //修改回显
  200. modify:function (items) {
  201. //重置
  202. app1.resets();
  203. //更新按钮
  204. app1.form='更新';
  205. //回显
  206. this.id=items.id;
  207. this.name=items.name;
  208. this.sex=items.sex;
  209. this.age=items.age;
  210. this.score=items.score;
  211. var arr=[];
  212. for(var i=0;i<items.hobby.length;i++){
  213. arr.push(items.hobby[i].id);
  214. }
  215. this.checkData=arr;
  216. this.isAdd=false;
  217. },
  218. update:function(items){
  219. axios.get('http://localhost:8080/updateStudent?id='+this.id+'&name='+this.name+'&sex='+this.sex+'&age='+
  220. this.age+'&score='+this.score+'&hobbys='+this.checkData)
  221. .then(function (response) {
  222. app1.getStudent();
  223. app1.resets();
  224. }).catch(function (error) {
  225. })
  226. },
  227. resets:function () {
  228. this.name='',
  229. this.sex='男',
  230. this.age='0',
  231. this.score=''
  232. this.checkData=[],
  233. this.form='提交',
  234. this.isAdd=true
  235. },
  236. checkedAll: function(){
  237. //全选和反选
  238. var _this = this;
  239. // .log(_this.checked+"---"+_this.checkList+"----"+_this.student)
  240. this.$nextTick(function() {
  241. if(!_this.checked){
  242. _this.checkList = _this.student.map(function(json,index){
  243. // console.log(json.id+","+index)
  244. return json.id;
  245. })
  246. }else {
  247. _this.checkList = []
  248. }
  249. });
  250. },
  251. }
  252. });
  253. </script>
  254. </body>
  255. </html>

application.properties配置文件
  1. # 热部署
  2. # 热部署生效
  3. spring.devtools.restart.enabled=true
  4. # 设置重启目录
  5. spring.devtools.restart.additional-paths=src/main/java
  6. #mybatis
  7. #mybatis-config.xml xml格式的mybatis配置
  8. #mybatis.configLocation=classpath:mybatis-config.xml
  9. # mybatis的SQL映射路径
  10. #mybatis.mapper-locaitons= classpath*:com/example/mapper/*.xml
  11. mybatis.mapper-locations=classpath:mappers/*.xml
  12. # 扫描package包
  13. mybatis.type-aliases-package=org.lanqiao.model
  14. # 开启驼峰命名转换:Table{create_time} -> Entity{createTime}
  15. mybatis.configuration.mapUnderscoreToCamelCase=true
  16. # 允许返回多个结果集
  17. mybatis.configuration.multipleResultSetsEnabled=true
  18. # 设置自增主键
  19. mybatis.configuration.useGeneratedKeys=true
  20. # 打印sql日志
  21. #mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  22. # 延迟加载总开关
  23. mybatis.configuration.lazyLoadingEnabled=false
  24. # 禁止积极主动的加载
  25. mybatis.configuration.aggressiveLazyLoading=false
  26. spring.datasource.url=jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&useSSL=false
  27. spring.datasource.username=root
  28. spring.datasource.password=123
  29. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  30. spring.datasource.max-idle=10
  31. spring.datasource.max-wait=10000
  32. spring.datasource.min-idle=5
  33. spring.datasource.initial-size=5
  34. spring.mvc.view.prefix=classpath:/static/
  35. spring.mvc.view.suffix=.html
  36. spring.mvc.static-path-pattern=/**

mapper生成接口和xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  3. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  4. <!-- 配置生成器 -->
  5. <generatorConfiguration>
  6. <context id="testTables" targetRuntime="MyBatis3" defaultModelType="flat">
  7. <property name="beginningDelimiter" value="`"/>
  8. <property name="endingDelimiter" value="`"/>
  9. <property name="javaFileEncoding" value="UTF-8"/>
  10. <!-- 生成注释配置 -->
  11. <commentGenerator>
  12. <!-- 是否去除自动生成的注释 true:是 : false:否 -->
  13. <property name="suppressAllComments" value="true"/>
  14. <property name="javaFileEncoding" value="UTF8"/>
  15. <!--生成的注释包含时间戳(避免重复提交SVN,设为true)-->
  16. <property name="suppressDate" value="true"/>
  17. </commentGenerator>
  18. <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
  19. <!--
  20. <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
  21. connectionURL="jdbc:oracle:thin:@150.16.17.22:1521/wsbs" userId="hr"
  22. password="hr123">
  23. </jdbcConnection>-->
  24. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  25. connectionURL="jdbc:mysql://localhost:3306/sys?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
  26. userId="root"
  27. password="123">
  28. </jdbcConnection>
  29. <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
  30. NUMERIC 类型解析为java.math.BigDecimal -->
  31. <javaTypeResolver>
  32. <property name="forceBigDecimals" value="false"/>
  33. </javaTypeResolver>
  34. <!-- targetProject:生成PO类的位置 -->
  35. <javaModelGenerator targetPackage="org.lanqiao.model"
  36. targetProject="E:/MyJAVA/SpringMakeup/src/main/java">
  37. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  38. <property name="enableSubPackages" value="false"/>
  39. <!-- 从数据库返回的值被清理前后的空格 -->
  40. <property name="trimStrings" value="true"/>
  41. </javaModelGenerator>
  42. <!-- targetProject:mapper.xml映射文件生成的位置 -->
  43. <sqlMapGenerator targetPackage="mappers"
  44. targetProject="E:/MyJAVA/SpringMakeup/src/main/resources">
  45. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  46. <property name="enableSubPackages" value="false"/>
  47. </sqlMapGenerator>
  48. <!-- targetPackage:mapper.java接口生成的位置 -->
  49. <javaClientGenerator type="XMLMAPPER"
  50. targetPackage="org.lanqiao.mapper"
  51. targetProject="E:/MyJAVA/SpringMakeup/src/main/java">
  52. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  53. <property name="enableSubPackages" value="false"/>
  54. </javaClientGenerator>
  55. <!-- 指定数据库表 -->
  56. <!-- enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
  57. enableSelectByExample="false" selectByExampleQueryId="false"-->
  58. <!--不生成example-->
  59. <!--<table tableName="items"></table> -->
  60. <table tableName="student" mapperName="StudentMapper" domainObjectName="Student"
  61. enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
  62. enableSelectByExample="false" selectByExampleQueryId="false">
  63. <!--下划线转驼峰命名-->
  64. <property name="useActualColumnNames" value="false"/>
  65. <!--指定自动生成主键的属性-->
  66. <generatedKey column="id" sqlStatement="MySql" identity="true"></generatedKey>
  67. <!--元素从将某些属性默认计算的值更改为指定的值。-->
  68. <!--<columnOverride column="message_content" javaType="List&lt;Teacher&gt;"></columnOverride >-->
  69. <!--忽略字段-->
  70. <!--<ignoreColumn column="file_id"></ignoreColumn>-->
  71. <!--<ignoreColumn column="lyric_id"></ignoreColumn>-->
  72. </table>
  73. </context>
  74. </generatorConfiguration>

读取生成文件的xml
  1. package org.lanqiao.test;
  2. import org.mybatis.generator.api.MyBatisGenerator;
  3. import org.mybatis.generator.config.Configuration;
  4. import org.mybatis.generator.config.xml.ConfigurationParser;
  5. import org.mybatis.generator.internal.DefaultShellCallback;
  6. import java.io.File;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. /**
  10. * @ClassName TestGenerator
  11. * @Description TODO
  12. * @Author lisonglin
  13. * @Date 2018/12/5 17:00
  14. * @Version 1.0
  15. */
  16. public class TestGenerator {
  17. /***
  18. * 功能描述:
  19. * 调用generatorConfig.xml
  20. * @param: []
  21. * @return: void
  22. * @auther: 李松林
  23. * @date: 2018/12/8 19:50
  24. */
  25. public void generator(){
  26. List<String> warnings=new ArrayList<String>();
  27. //更新数据库时,请修改项目的xml配置绝对路径
  28. File file=new File("E:\\MyJAVA\\SpringMakeup\\src\\main\\conf\\generatorConfig.xml");
  29. ConfigurationParser cp = new ConfigurationParser(warnings);
  30. Configuration config = null;
  31. try {
  32. config = cp.parseConfiguration(file);
  33. DefaultShellCallback shellCallback = new DefaultShellCallback(true);
  34. MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, shellCallback, warnings);
  35. myBatisGenerator.generate(null);
  36. System.out.println(warnings);
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. /**
  42. *
  43. * @param args
  44. * @throws Exception
  45. */
  46. public static void main(String[] args) throws Exception {
  47. try {
  48. TestGenerator generatorSqlmap = new TestGenerator();
  49. generatorSqlmap.generator();
  50. } catch (Exception e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }

student的增删改查xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="org.lanqiao.mapper.StudentMapper">
  4. <resultMap id="BaseResultMap" type="org.lanqiao.model.Student">
  5. <id column="id" property="id" />
  6. <result column="name" jdbcType="VARCHAR" property="name" />
  7. <result column="sex" jdbcType="VARCHAR" property="sex" />
  8. <result column="age" property="age" />
  9. <result column="score" jdbcType="DOUBLE" property="score" />
  10. </resultMap>
  11. <sql id="Base_Column_List">
  12. id, name, sex, age, score
  13. </sql>
  14. <sql id="Base_All">
  15. select s.id sid,s.`name`,s.sex,s.age,s.score,h.id,h.hobby
  16. from student s
  17. join stu_hobby sh
  18. on s.id=sh.id
  19. join hobbys h
  20. on sh.hobby=h.id
  21. </sql>
  22. <select id="getAll" resultMap="getStudentAll">
  23. <include refid="Base_All"></include>
  24. </select>
  25. <resultMap id="getStudentAll" type="Student">
  26. <id column="sid" property="id"></id>
  27. <result column="name" property="name"></result>
  28. <result column="sex" property="sex"></result>
  29. <result column="age" property="age"></result>
  30. <result column="score" property="score"></result>
  31. <collection property="hobby" ofType="Hobbys">
  32. <id column="id" property="id"></id>
  33. <result column="hobby" property="hobby"></result>
  34. </collection>
  35. </resultMap>
  36. <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
  37. select
  38. <include refid="Base_Column_List" />
  39. from student
  40. where id = #{id,jdbcType=INTEGER}
  41. </select>
  42. <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
  43. delete from student
  44. where id = #{id,jdbcType=INTEGER}
  45. </delete>
  46. <insert id="insert" parameterType="org.lanqiao.model.Student">
  47. <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
  48. SELECT LAST_INSERT_ID()
  49. </selectKey>
  50. insert into student (name, sex, age,
  51. score)
  52. values (#{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
  53. #{score,jdbcType=DOUBLE})
  54. </insert>
  55. <insert id="insertSelective" parameterType="org.lanqiao.model.Student">
  56. <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
  57. SELECT LAST_INSERT_ID()
  58. </selectKey>
  59. insert into student
  60. <trim prefix="(" suffix=")" suffixOverrides=",">
  61. <if test="name != null">
  62. name,
  63. </if>
  64. <if test="sex != null">
  65. sex,
  66. </if>
  67. <if test="age != null">
  68. age,
  69. </if>
  70. <if test="score != null">
  71. score,
  72. </if>
  73. </trim>
  74. <trim prefix="values (" suffix=")" suffixOverrides=",">
  75. <if test="name != null">
  76. #{name,jdbcType=VARCHAR},
  77. </if>
  78. <if test="sex != null">
  79. #{sex,jdbcType=VARCHAR},
  80. </if>
  81. <if test="age != null">
  82. #{age,jdbcType=INTEGER},
  83. </if>
  84. <if test="score != null">
  85. #{score,jdbcType=DOUBLE},
  86. </if>
  87. </trim>
  88. </insert>
  89. <update id="updateByPrimaryKeySelective" parameterType="org.lanqiao.model.Student">
  90. update student
  91. <set>
  92. <if test="name != null">
  93. name = #{name,jdbcType=VARCHAR},
  94. </if>
  95. <if test="sex != null">
  96. sex = #{sex,jdbcType=VARCHAR},
  97. </if>
  98. <if test="age != null">
  99. age = #{age,jdbcType=INTEGER},
  100. </if>
  101. <if test="score != null">
  102. score = #{score,jdbcType=DOUBLE},
  103. </if>
  104. </set>
  105. where id = #{id,jdbcType=INTEGER}
  106. </update>
  107. <update id="updateByPrimaryKey" parameterType="org.lanqiao.model.Student">
  108. update student
  109. set name = #{name,jdbcType=VARCHAR},
  110. sex = #{sex,jdbcType=VARCHAR},
  111. age = #{age,jdbcType=INTEGER},
  112. score = #{score,jdbcType=DOUBLE}
  113. where id = #{id,jdbcType=INTEGER}
  114. </update>
  115. </mapper>

自己写个兴趣和学生中间表sql
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="org.lanqiao.mapper.HobbysMapper">
  4. <select id="getHobbys" resultType="Hobbys">
  5. select * from hobbys where id = #{id,jdbcType=INTEGER}
  6. </select>
  7. <select id="getHobbis" resultType="Hobbys">
  8. select * from hobbys where id=#{id,jdbcType=INTEGER}
  9. </select>
  10. </mapper>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="org.lanqiao.mapper.StudentHobbysMapper">
  4. <insert id="insertStudentHobby">
  5. insert into stu_hobby (id,hobby) values (#{studentId},#{hobbyId})
  6. </insert>
  7. <delete id="deleteHobbyIdToStudent">
  8. delete from stu_hobby where id=#{studentId}
  9. </delete>
  10. </mapper>

model编写
  1. package org.lanqiao.model;
  2. import java.io.Serializable;
  3. public class Hobbys implements Serializable {
  4. /**
  5. *
  6. */
  7. private static final long serialVersionUID = 1L;
  8. private Integer id;
  9. /** 兴趣 */
  10. private String hobby;
  11. public Integer getId() {
  12. return id;
  13. }
  14. public void setId(Integer id) {
  15. this.id = id;
  16. }
  17. public String getHobby() {
  18. return hobby;
  19. }
  20. public void setHobby(String hobby) {
  21. this.hobby = hobby == null ? null : hobby.trim();
  22. }
  23. @Override
  24. public String toString() {
  25. return "Hobbys [id=" + id + ", hobby=" + hobby + "]";
  26. }
  27. }
  1. package org.lanqiao.model;
  2. import javax.validation.constraints.NotNull;
  3. import java.io.Serializable;
  4. import java.util.List;
  5. public class Student implements Serializable {
  6. private Integer id;
  7. @NotNull(message = "姓名不能为空")
  8. private String name;
  9. private String sex;
  10. private Integer age;
  11. private Double score;
  12. private List<Hobbys> hobby;
  13. public Integer getId() {
  14. return id;
  15. }
  16. public void setId(Integer id) {
  17. this.id = id;
  18. }
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name == null ? null : name.trim();
  24. }
  25. public String getSex() {
  26. return sex;
  27. }
  28. public void setSex(String sex) {
  29. this.sex = sex == null ? null : sex.trim();
  30. }
  31. public Integer getAge() {
  32. return age;
  33. }
  34. public void setAge(Integer age) {
  35. this.age = age;
  36. }
  37. public Double getScore() {
  38. return score;
  39. }
  40. public void setScore(Double score) {
  41. this.score = score;
  42. }
  43. public List<Hobbys> getHobby() {
  44. return hobby;
  45. }
  46. public void setHobby(List<Hobbys> hobby) {
  47. this.hobby = hobby;
  48. }
  49. @Override
  50. public String toString() {
  51. return "Student{" +
  52. "id=" + id +
  53. ", name='" + name + '\'' +
  54. ", sex='" + sex + '\'' +
  55. ", age=" + age +
  56. ", score=" + score +
  57. ", hobby=" + hobby +
  58. '}';
  59. }
  60. public Student(Integer id, @NotNull(message = "姓名不能为空") String name, List<Hobbys> hobby) {
  61. super();
  62. this.id = id;
  63. this.name = name;
  64. this.hobby = hobby;
  65. }
  66. }
  1. package org.lanqiao.model;
  2. /**
  3. * @ClassName ResponseCode
  4. * @Description TODO
  5. * @Author lisonglin
  6. * @Date 2019/3/31 11:32
  7. * @Version 1.0
  8. */
  9. public class ResponseCode {
  10. private int errcode;
  11. private String errmsg;
  12. private Object data;
  13. public int getErrcode() {
  14. return errcode;
  15. }
  16. public void setErrcode(int errcode) {
  17. this.errcode = errcode;
  18. }
  19. public String getErrmsg() {
  20. return errmsg;
  21. }
  22. public void setErrmsg(String errmsg) {
  23. this.errmsg = errmsg;
  24. }
  25. public Object getData() {
  26. return data;
  27. }
  28. public void setData(Object data) {
  29. this.data = data;
  30. }
  31. public ResponseCode(int errcode, String errmsg, Object data) {
  32. this.errcode = errcode;
  33. this.errmsg = errmsg;
  34. this.data = data;
  35. }
  36. public ResponseCode(int errcode, String errmsg) {
  37. this.errcode = errcode;
  38. this.errmsg = errmsg;
  39. }
  40. public ResponseCode() {
  41. }
  42. public ResponseCode(Object data) {
  43. this.data = data;
  44. }
  45. public ResponseCode(int errcode) {
  46. this.errcode = errcode;
  47. }
  48. public static ResponseCode OK(Object data) {
  49. return new ResponseCode(0, "ok", data);
  50. }
  51. }

mapper接口生成
  1. package org.lanqiao.mapper;
  2. import org.lanqiao.model.Student;
  3. import org.springframework.stereotype.Component;
  4. import java.util.List;
  5. @Component
  6. public interface StudentMapper {
  7. List<Student> getAll();
  8. int deleteByPrimaryKey(Integer id);
  9. int insert(Student record);
  10. int insertSelective(Student record);
  11. Student selectByPrimaryKey(Integer id);
  12. int updateByPrimaryKeySelective(Student record);
  13. int updateByPrimaryKey(Student record);
  14. }
  1. package org.lanqiao.mapper;
  2. import org.lanqiao.model.Hobbys;
  3. import org.springframework.stereotype.Component;
  4. import java.util.List;
  5. @Component
  6. public interface HobbysMapper {
  7. Hobbys getHobbys(Hobbys hobbys );
  8. // Hobbys getHobbis(Hobbys hobbys );
  9. }
  1. package org.lanqiao.mapper;
  2. import org.apache.ibatis.annotations.Param;
  3. import org.lanqiao.model.Hobbys;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * @ClassName StudentHobbysMapper
  7. * @Description TODO
  8. * @Author lisonglin
  9. * @Date 2019/3/30 11:41
  10. * @Version 1.0
  11. */
  12. @Component
  13. public interface StudentHobbysMapper {
  14. void insertStudentHobby(@Param("studentId")Integer studentId,@Param("hobbyId") String hobbyId);
  15. void deleteHobbyIdToStudent(@Param("studentId") Integer id);
  16. }

dao层编写
  1. @Repository
  2. public class HobbysDao{
  3. @Autowired
  4. HobbysMapper hobbysMapper;
  5. public Hobbys getHobbys(Hobbys hobbys) {
  6. return hobbysMapper.getHobbys(hobbys);
  7. }
  8. }
  1. @Repository
  2. public class StudentDao {
  3. @Autowired
  4. StudentMapper studentMapper;
  5. @Autowired
  6. StudentHobbysMapper studentHobbysMapper;
  7. public int deleteByPrimaryKey(Integer id){
  8. studentMapper.deleteByPrimaryKey(id);
  9. studentHobbysMapper.deleteHobbyIdToStudent(id);
  10. return 1;
  11. };
  12. public int insertStudent(Student student, String hobbys){
  13. studentMapper.insert(student);
  14. String regex = ",";
  15. String[] arr = hobbys.split(regex);
  16. for(int i=0;i<arr.length;i++){
  17. studentHobbysMapper.insertStudentHobby(student.getId(),arr[i]);
  18. }
  19. return 1;
  20. };
  21. public int insertSelective(Student record){
  22. return studentMapper.insertSelective(record);
  23. };
  24. public Student selectByPrimaryKey(Integer id){
  25. return studentMapper.selectByPrimaryKey(id);
  26. };
  27. public int updateByPrimaryKeySelective(Student record){
  28. return studentMapper.updateByPrimaryKeySelective(record);
  29. };
  30. public int updateByPrimaryKey(Student student, String hobbys){
  31. studentMapper.updateByPrimaryKey(student);
  32. studentHobbysMapper.deleteHobbyIdToStudent(student.getId());
  33. String regex = ",";
  34. String[] arr = hobbys.split(regex);
  35. for(int i=0;i<arr.length;i++){
  36. studentHobbysMapper.insertStudentHobby(student.getId(),arr[i]);
  37. }
  38. return 1;
  39. };
  40. public List<Student> getAll() {
  41. return studentMapper.getAll();
  42. }
  43. }

service层编写
  1. @Service
  2. public class HobbysService {
  3. @Autowired
  4. HobbysDao hobbysDao;
  5. public Hobbys getHobbys(Hobbys hobbys){
  6. return hobbysDao.getHobbys(hobbys);
  7. }
  8. }
  1. @Service
  2. public class StudentService{
  3. @Autowired
  4. StudentDao studentDao;
  5. public List<Student> getAll() {
  6. return studentDao.getAll();
  7. }
  8. @Transactional(isolation = Isolation.READ_COMMITTED, readOnly = false, rollbackFor = Exception.class)
  9. public int deleteByPrimaryKey(Integer id){
  10. return studentDao.deleteByPrimaryKey(id);
  11. }
  12. @Transactional(isolation = Isolation.READ_COMMITTED, readOnly = false, rollbackFor = Exception.class)
  13. public int insert(Student record,String hobbys){
  14. return studentDao.insertStudent(record,hobbys);
  15. }
  16. public int insertSelective(Student record){
  17. return studentDao.insertSelective(record);
  18. }
  19. public Student selectByPrimaryKey(Integer id){
  20. return studentDao.selectByPrimaryKey(id);
  21. }
  22. @Transactional(isolation = Isolation.READ_COMMITTED, readOnly = false, rollbackFor = Exception.class)
  23. public int updateByPrimaryKeySelective(Student record){
  24. return studentDao.updateByPrimaryKeySelective(record);
  25. }
  26. @Transactional(isolation = Isolation.READ_COMMITTED, readOnly = false, rollbackFor = Exception.class)
  27. public int updateByPrimaryKey(Student record, String hobbys){
  28. return studentDao.updateByPrimaryKey(record,hobbys);
  29. }
  30. }

controller层编写
  1. @Controller
  2. public class MainController {
  3. @Autowired
  4. StudentService studentService;
  5. @Autowired
  6. HobbysService hobbysService;
  7. @ResponseBody
  8. @RequestMapping("/getAll")
  9. public List<Student> getStudent(){
  10. List<Student> students = studentService.getAll();
  11. System.out.println(students);
  12. return students;
  13. }
  14. @ResponseBody
  15. @RequestMapping(value ="/addStudent")
  16. public ResponseCode addStudent(@Valid Student student, String hobbys){
  17. System.out.println(student.toString());
  18. System.out.println("兴趣是:"+hobbys);
  19. int insert = studentService.insert(student,hobbys);
  20. return new ResponseCode(insert);
  21. }
  22. @ResponseBody
  23. @RequestMapping(value ="/updateStudent")
  24. public ResponseCode updateStudent(@Valid Student student,String hobbys){
  25. System.out.println(student+"兴趣:"+hobbys);
  26. int i = studentService.updateByPrimaryKey(student, hobbys);
  27. return new ResponseCode(i);
  28. }
  29. @ResponseBody
  30. @RequestMapping(value ="/deleteStudent")
  31. public ResponseCode deleteStudent(Integer studentId){
  32. int i = studentService.deleteByPrimaryKey(studentId);
  33. return new ResponseCode(i);
  34. }
  35. @ResponseBody
  36. @RequestMapping("/getHobbys")
  37. public List<Hobbys> getHobbys(){
  38. return hobbysService.getHobbys();
  39. }
  40. @RequestMapping("/hello")
  41. public String hello(){
  42. return "hello";
  43. }
  44. }

config层编写

解决跨域请求配置
  1. @Configuration
  2. public class AccessConfig extends WebMvcConfigurationSupport {
  3. @Override
  4. public void addCorsMappings(CorsRegistry registry) {
  5. registry.addMapping("/**")
  6. .allowedOrigins("*")
  7. .allowedHeaders("*")
  8. .allowCredentials(true)
  9. .allowedMethods("GET", "POST", "DELETE", "PUT")
  10. .maxAge(3600);
  11. }
  12. }

扫描mapper接口
  1. @Configuration
  2. public class MapperScannerConfig {
  3. @Bean
  4. public MapperScannerConfigurer mapperScannerConfigurer() {
  5. MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
  6. //指定xml配置文件的路径
  7. mapperScannerConfigurer.setBasePackage("org.lanqiao.mapper");
  8. return mapperScannerConfigurer;
  9. }
  10. }

1.6 对应博客地址

https://blog.csdn.net/qq_41520636/article/details/88929298

1.7 启动环境

  • JDK1.8
  • IDEA
  • WINDOWS10
  • MAVEN

启动main方法

  1. @SpringBootApplication
  2. @EnableTransactionManagement
  3. @ComponentScan(basePackages = "org.lanqiao.*")
  4. public class DemoApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(DemoApplication.class, args);
  7. }
  8. }