SpringBoot入门构建Web应用程序
1.1 技术介绍
Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。
1.2 技术注意点
a.springboot生成环境部署,热部署插件不要使用,去除springs-boot-devtools
b.监控相关的jar包去除,
spring-boot-starter-actuator 的监控
druid 的监控
swagger的接口
c.打包一定要跳过测试test
1.3 技术具体demo文件路径
E:\MyJAVA\SpringMakeup
1.4 demo的UML图
1.5 demo的技术代码实现
pom准备
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- tomcat的支持. -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--自动生成bean -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
<!-- 对象转换成json引入如下依赖 -->
<!-- 文档:https://www.yiibai.com/jackson/jackson_first_application.html#article-start -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
vue编写
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>vue增删改查</title>
</head>
<body>
<div id="app1">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" align="center">学生基本信息</td>
</tr>
<tr>
<td>姓名</td>
<td>
<input v-model="name" style="width:150px" />
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" id="boy" value="男" v-model="sex">
<label for="boy">男</label>
<input type="radio" id="girl" value="女" v-model="sex">
<label for="girl">女</label>
</td>
</tr>
<tr>
<td>年龄</td>
<td>
<select v-model="age">
<option v-for="option in options" v-bind:value="option.value"
:disabled="option.value==0?true:false" :class="{statusbtn:option.value==0}">
{{ option.text }}
</option>
</select>
</td>
</tr>
<tr>
<td>成绩</td>
<td>
<input v-model.number="score" placeholder="请输入成绩" style="width:150px"/>
</td>
</tr>
<tr>
<td>兴趣</td>
<td>
<span v-for="(studentHobby,index) in studentHobbys" >
<input type="checkbox" name="interests" v-bind:value="index+1" v-model="checkData">
<label>{{ studentHobby.hobby }}</label>
</span>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" :value="form" @click="submission" v-if="isAdd"/>
<input type="submit" :value="form" @click="update" v-else="!isAdd"/>
<input type="submit" id="reset" value="重置" v-on:click="resets"/>
</td>
</tr>
</table>
<br /><br /><br /><br />
<table border="1" cellspacing="0" cellpadding="0" id="listTable">
<tr>
<td>选中</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>成绩</td>
<td>兴趣</td>
<td>操作</td>
</tr>
<tr>
<td>
<label>全选</label>
<input type="checkbox" name="item" v-model='checked' v-on:click='checkedAll'/>
</td>
<td colspan="6" align="center">
<input type="button" value="选中删除" @click="delRow"/>
</td>
</tr>
<tr v-for="(items,index) in student">
<td><input type="checkbox" name="item" v-model="checkList" :value="items.id"/>{{1 + index}}</td>
<td>{{items.name}}</td>
<td>{{items.sex}}</td>
<td>{{items.age}}</td>
<td>{{ items.score }}</td>
<td><span v-for="item in items.hobby">{{item.hobby}} </span></td>
<td>
<input type="button" value="删除" @click="del(items.id)"/>
<input type="button" name="update" value="修改" @click="modify(items)" />
</td>
</tr>
</table>
</div>
<style>
.statusbtn {
color: #d6caca;
cursor: not-allowed; /*这个在button上面才管用,是一个禁用的小标识*/
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.bootcss.com/qs/6.6.0/qs.min.js"></script>
<script>
var app1=new Vue({
el:'#app1',
data:{
options: [
{ text: '请选择', value: '0' },
{ text: '16', value: '16' },
{ text: '17', value: '17' },
{ text: '18', value: '18' },
{ text: '19', value: '19' },
{ text: '20', value: '20' },
{ text: '21', value: '21' },
{ text: '22', value: '22' },
{ text: '23', value: '23' },
],
id:'',
name:'',
age:'0',
sex:'男',
score:'',
studentHobbys:[],
student:[],
form:'提交',
isAdd: true,
checkData: [],//后台请求的数据
checked:false,//全选框
checkList: []
},
watch: { // 监视双向绑定的数据数组
'checkList': {
handler(val, oldVal){ // 数据数组有变化将触发此函数
if (val.length === this.student.length) {
this.checked = true;
} else {
this.checked = false;
}
},
deep: true // 深度监视
}
},
created: function (){
this.getStudent();
this.getHobbysAll();
},
methods: {
getHobbysAll: function(){
axios.get('http://localhost:8080/getHobbys')
.then(function (response) {
var arr = response.data;
app1.studentHobbys = arr;
})
.catch(function (error) {
})
},
getStudent:function () {
axios.post('http://localhost:8080/getAll').
then(function (response){
var arr=response.data;
app1.student=arr;
}) .catch(function (error) {
})
},
submission:function () {
// console.log("选中:"+this.checkData);
//获取兴趣
var selectedValue=this.checkData;
axios.get('http://localhost:8080/addStudent?name='+this.name+'&sex='+this.sex+'&age='+
this.age+'&score='+this.score+'&hobbys='+selectedValue)
.then(function (response) {
//更新
app1.getStudent();
//重置
app1.resets();
}).catch(function (error) {
})
},
del:function (e) {
// console.log(e);
axios.get('http://localhost:8080/deleteStudent?studentId='+e)
.then(function (response) {
app1.getStudent();
}).catch(function (error) {
})
},
//选中删除
delRow:function(){
for(var i=0;i<this.checkList.length;i++){
axios.get('http://localhost:8080/deleteStudent?studentId='+this.checkList[i])
.then(function (response) {
app1.getStudent();
}).catch(function (error) {
})
}
},
//修改回显
modify:function (items) {
//重置
app1.resets();
//更新按钮
app1.form='更新';
//回显
this.id=items.id;
this.name=items.name;
this.sex=items.sex;
this.age=items.age;
this.score=items.score;
var arr=[];
for(var i=0;i<items.hobby.length;i++){
arr.push(items.hobby[i].id);
}
this.checkData=arr;
this.isAdd=false;
},
update:function(items){
axios.get('http://localhost:8080/updateStudent?id='+this.id+'&name='+this.name+'&sex='+this.sex+'&age='+
this.age+'&score='+this.score+'&hobbys='+this.checkData)
.then(function (response) {
app1.getStudent();
app1.resets();
}).catch(function (error) {
})
},
resets:function () {
this.name='',
this.sex='男',
this.age='0',
this.score=''
this.checkData=[],
this.form='提交',
this.isAdd=true
},
checkedAll: function(){
//全选和反选
var _this = this;
// .log(_this.checked+"---"+_this.checkList+"----"+_this.student)
this.$nextTick(function() {
if(!_this.checked){
_this.checkList = _this.student.map(function(json,index){
// console.log(json.id+","+index)
return json.id;
})
}else {
_this.checkList = []
}
});
},
}
});
</script>
</body>
</html>
application.properties配置文件
# 热部署
# 热部署生效
spring.devtools.restart.enabled=true
# 设置重启目录
spring.devtools.restart.additional-paths=src/main/java
#mybatis
#mybatis-config.xml xml格式的mybatis配置
#mybatis.configLocation=classpath:mybatis-config.xml
# mybatis的SQL映射路径
#mybatis.mapper-locaitons= classpath*:com/example/mapper/*.xml
mybatis.mapper-locations=classpath:mappers/*.xml
# 扫描package包
mybatis.type-aliases-package=org.lanqiao.model
# 开启驼峰命名转换:Table{create_time} -> Entity{createTime}
mybatis.configuration.mapUnderscoreToCamelCase=true
# 允许返回多个结果集
mybatis.configuration.multipleResultSetsEnabled=true
# 设置自增主键
mybatis.configuration.useGeneratedKeys=true
# 打印sql日志
#mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 延迟加载总开关
mybatis.configuration.lazyLoadingEnabled=false
# 禁止积极主动的加载
mybatis.configuration.aggressiveLazyLoading=false
spring.datasource.url=jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.mvc.view.prefix=classpath:/static/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/**
mapper生成接口和xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 生成注释配置 -->
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
<property name="javaFileEncoding" value="UTF8"/>
<!--生成的注释包含时间戳(避免重复提交SVN,设为true)-->
<property name="suppressDate" value="true"/>
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<!--
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@150.16.17.22:1521/wsbs" userId="hr"
password="hr123">
</jdbcConnection>-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&useSSL=false"
userId="root"
password="123">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="org.lanqiao.model"
targetProject="E:/MyJAVA/SpringMakeup/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper.xml映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mappers"
targetProject="E:/MyJAVA/SpringMakeup/src/main/resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper.java接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="org.lanqiao.mapper"
targetProject="E:/MyJAVA/SpringMakeup/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<!-- enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"-->
<!--不生成example-->
<!--<table tableName="items"></table> -->
<table tableName="student" mapperName="StudentMapper" domainObjectName="Student"
enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
<!--下划线转驼峰命名-->
<property name="useActualColumnNames" value="false"/>
<!--指定自动生成主键的属性-->
<generatedKey column="id" sqlStatement="MySql" identity="true"></generatedKey>
<!--元素从将某些属性默认计算的值更改为指定的值。-->
<!--<columnOverride column="message_content" javaType="List<Teacher>"></columnOverride >-->
<!--忽略字段-->
<!--<ignoreColumn column="file_id"></ignoreColumn>-->
<!--<ignoreColumn column="lyric_id"></ignoreColumn>-->
</table>
</context>
</generatorConfiguration>
读取生成文件的xml
package org.lanqiao.test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName TestGenerator
* @Description TODO
* @Author lisonglin
* @Date 2018/12/5 17:00
* @Version 1.0
*/
public class TestGenerator {
/***
* 功能描述:
* 调用generatorConfig.xml
* @param: []
* @return: void
* @auther: 李松林
* @date: 2018/12/8 19:50
*/
public void generator(){
List<String> warnings=new ArrayList<String>();
//更新数据库时,请修改项目的xml配置绝对路径
File file=new File("E:\\MyJAVA\\SpringMakeup\\src\\main\\conf\\generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = null;
try {
config = cp.parseConfiguration(file);
DefaultShellCallback shellCallback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, shellCallback, warnings);
myBatisGenerator.generate(null);
System.out.println(warnings);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
try {
TestGenerator generatorSqlmap = new TestGenerator();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
student的增删改查xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lanqiao.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="org.lanqiao.model.Student">
<id column="id" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="age" property="age" />
<result column="score" jdbcType="DOUBLE" property="score" />
</resultMap>
<sql id="Base_Column_List">
id, name, sex, age, score
</sql>
<sql id="Base_All">
select s.id sid,s.`name`,s.sex,s.age,s.score,h.id,h.hobby
from student s
join stu_hobby sh
on s.id=sh.id
join hobbys h
on sh.hobby=h.id
</sql>
<select id="getAll" resultMap="getStudentAll">
<include refid="Base_All"></include>
</select>
<resultMap id="getStudentAll" type="Student">
<id column="sid" property="id"></id>
<result column="name" property="name"></result>
<result column="sex" property="sex"></result>
<result column="age" property="age"></result>
<result column="score" property="score"></result>
<collection property="hobby" ofType="Hobbys">
<id column="id" property="id"></id>
<result column="hobby" property="hobby"></result>
</collection>
</resultMap>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from student
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="org.lanqiao.model.Student">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into student (name, sex, age,
score)
values (#{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{score,jdbcType=DOUBLE})
</insert>
<insert id="insertSelective" parameterType="org.lanqiao.model.Student">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name,
</if>
<if test="sex != null">
sex,
</if>
<if test="age != null">
age,
</if>
<if test="score != null">
score,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
<if test="score != null">
#{score,jdbcType=DOUBLE},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="org.lanqiao.model.Student">
update student
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
<if test="score != null">
score = #{score,jdbcType=DOUBLE},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="org.lanqiao.model.Student">
update student
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
score = #{score,jdbcType=DOUBLE}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
自己写个兴趣和学生中间表sql
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lanqiao.mapper.HobbysMapper">
<select id="getHobbys" resultType="Hobbys">
select * from hobbys where id = #{id,jdbcType=INTEGER}
</select>
<select id="getHobbis" resultType="Hobbys">
select * from hobbys where id=#{id,jdbcType=INTEGER}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lanqiao.mapper.StudentHobbysMapper">
<insert id="insertStudentHobby">
insert into stu_hobby (id,hobby) values (#{studentId},#{hobbyId})
</insert>
<delete id="deleteHobbyIdToStudent">
delete from stu_hobby where id=#{studentId}
</delete>
</mapper>
model编写
package org.lanqiao.model;
import java.io.Serializable;
public class Hobbys implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
/** 兴趣 */
private String hobby;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby == null ? null : hobby.trim();
}
@Override
public String toString() {
return "Hobbys [id=" + id + ", hobby=" + hobby + "]";
}
}
package org.lanqiao.model;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
public class Student implements Serializable {
private Integer id;
@NotNull(message = "姓名不能为空")
private String name;
private String sex;
private Integer age;
private Double score;
private List<Hobbys> hobby;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public List<Hobbys> getHobby() {
return hobby;
}
public void setHobby(List<Hobbys> hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", score=" + score +
", hobby=" + hobby +
'}';
}
public Student(Integer id, @NotNull(message = "姓名不能为空") String name, List<Hobbys> hobby) {
super();
this.id = id;
this.name = name;
this.hobby = hobby;
}
}
package org.lanqiao.model;
/**
* @ClassName ResponseCode
* @Description TODO
* @Author lisonglin
* @Date 2019/3/31 11:32
* @Version 1.0
*/
public class ResponseCode {
private int errcode;
private String errmsg;
private Object data;
public int getErrcode() {
return errcode;
}
public void setErrcode(int errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public ResponseCode(int errcode, String errmsg, Object data) {
this.errcode = errcode;
this.errmsg = errmsg;
this.data = data;
}
public ResponseCode(int errcode, String errmsg) {
this.errcode = errcode;
this.errmsg = errmsg;
}
public ResponseCode() {
}
public ResponseCode(Object data) {
this.data = data;
}
public ResponseCode(int errcode) {
this.errcode = errcode;
}
public static ResponseCode OK(Object data) {
return new ResponseCode(0, "ok", data);
}
}
mapper接口生成
package org.lanqiao.mapper;
import org.lanqiao.model.Student;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface StudentMapper {
List<Student> getAll();
int deleteByPrimaryKey(Integer id);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
}
package org.lanqiao.mapper;
import org.lanqiao.model.Hobbys;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface HobbysMapper {
Hobbys getHobbys(Hobbys hobbys );
// Hobbys getHobbis(Hobbys hobbys );
}
package org.lanqiao.mapper;
import org.apache.ibatis.annotations.Param;
import org.lanqiao.model.Hobbys;
import org.springframework.stereotype.Component;
/**
* @ClassName StudentHobbysMapper
* @Description TODO
* @Author lisonglin
* @Date 2019/3/30 11:41
* @Version 1.0
*/
@Component
public interface StudentHobbysMapper {
void insertStudentHobby(@Param("studentId")Integer studentId,@Param("hobbyId") String hobbyId);
void deleteHobbyIdToStudent(@Param("studentId") Integer id);
}
dao层编写
@Repository
public class HobbysDao{
@Autowired
HobbysMapper hobbysMapper;
public Hobbys getHobbys(Hobbys hobbys) {
return hobbysMapper.getHobbys(hobbys);
}
}
@Repository
public class StudentDao {
@Autowired
StudentMapper studentMapper;
@Autowired
StudentHobbysMapper studentHobbysMapper;
public int deleteByPrimaryKey(Integer id){
studentMapper.deleteByPrimaryKey(id);
studentHobbysMapper.deleteHobbyIdToStudent(id);
return 1;
};
public int insertStudent(Student student, String hobbys){
studentMapper.insert(student);
String regex = ",";
String[] arr = hobbys.split(regex);
for(int i=0;i<arr.length;i++){
studentHobbysMapper.insertStudentHobby(student.getId(),arr[i]);
}
return 1;
};
public int insertSelective(Student record){
return studentMapper.insertSelective(record);
};
public Student selectByPrimaryKey(Integer id){
return studentMapper.selectByPrimaryKey(id);
};
public int updateByPrimaryKeySelective(Student record){
return studentMapper.updateByPrimaryKeySelective(record);
};
public int updateByPrimaryKey(Student student, String hobbys){
studentMapper.updateByPrimaryKey(student);
studentHobbysMapper.deleteHobbyIdToStudent(student.getId());
String regex = ",";
String[] arr = hobbys.split(regex);
for(int i=0;i<arr.length;i++){
studentHobbysMapper.insertStudentHobby(student.getId(),arr[i]);
}
return 1;
};
public List<Student> getAll() {
return studentMapper.getAll();
}
}
service层编写
@Service
public class HobbysService {
@Autowired
HobbysDao hobbysDao;
public Hobbys getHobbys(Hobbys hobbys){
return hobbysDao.getHobbys(hobbys);
}
}
@Service
public class StudentService{
@Autowired
StudentDao studentDao;
public List<Student> getAll() {
return studentDao.getAll();
}
@Transactional(isolation = Isolation.READ_COMMITTED, readOnly = false, rollbackFor = Exception.class)
public int deleteByPrimaryKey(Integer id){
return studentDao.deleteByPrimaryKey(id);
}
@Transactional(isolation = Isolation.READ_COMMITTED, readOnly = false, rollbackFor = Exception.class)
public int insert(Student record,String hobbys){
return studentDao.insertStudent(record,hobbys);
}
public int insertSelective(Student record){
return studentDao.insertSelective(record);
}
public Student selectByPrimaryKey(Integer id){
return studentDao.selectByPrimaryKey(id);
}
@Transactional(isolation = Isolation.READ_COMMITTED, readOnly = false, rollbackFor = Exception.class)
public int updateByPrimaryKeySelective(Student record){
return studentDao.updateByPrimaryKeySelective(record);
}
@Transactional(isolation = Isolation.READ_COMMITTED, readOnly = false, rollbackFor = Exception.class)
public int updateByPrimaryKey(Student record, String hobbys){
return studentDao.updateByPrimaryKey(record,hobbys);
}
}
controller层编写
@Controller
public class MainController {
@Autowired
StudentService studentService;
@Autowired
HobbysService hobbysService;
@ResponseBody
@RequestMapping("/getAll")
public List<Student> getStudent(){
List<Student> students = studentService.getAll();
System.out.println(students);
return students;
}
@ResponseBody
@RequestMapping(value ="/addStudent")
public ResponseCode addStudent(@Valid Student student, String hobbys){
System.out.println(student.toString());
System.out.println("兴趣是:"+hobbys);
int insert = studentService.insert(student,hobbys);
return new ResponseCode(insert);
}
@ResponseBody
@RequestMapping(value ="/updateStudent")
public ResponseCode updateStudent(@Valid Student student,String hobbys){
System.out.println(student+"兴趣:"+hobbys);
int i = studentService.updateByPrimaryKey(student, hobbys);
return new ResponseCode(i);
}
@ResponseBody
@RequestMapping(value ="/deleteStudent")
public ResponseCode deleteStudent(Integer studentId){
int i = studentService.deleteByPrimaryKey(studentId);
return new ResponseCode(i);
}
@ResponseBody
@RequestMapping("/getHobbys")
public List<Hobbys> getHobbys(){
return hobbysService.getHobbys();
}
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
config层编写
解决跨域请求配置
@Configuration
public class AccessConfig extends WebMvcConfigurationSupport {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
扫描mapper接口
@Configuration
public class MapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//指定xml配置文件的路径
mapperScannerConfigurer.setBasePackage("org.lanqiao.mapper");
return mapperScannerConfigurer;
}
}
1.6 对应博客地址
https://blog.csdn.net/qq_41520636/article/details/88929298
1.7 启动环境
- JDK1.8
- IDEA
- WINDOWS10
- MAVEN
启动main方法
@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = "org.lanqiao.*")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}