admin管理员组文章数量:1530022
你想要的SpringBoot, 都在这里!
- 一,简化开发过程
- 二,特性快速创建,
- 三,四大核心
- 四,开发环境
- 五,第一个spring boot程序
- 七,第一个springboot程序解析
- 八,springboot的核心配置文件
- 九,多配置文件
- 十,自定义配置
- 在springboot的核心配置文件中自定义配置,然后采用注解读取属性值
- 第二种方法
- 十二, springboot下的springmvc
- 十三, springboot下使用jsp
- 十四,springboot继承mybatis
- 十五,SpringBoot下事务配置管理
- 十六,Springboot实现RestFull
- 十七,SpringBoot的热部署插件
- 十八,因为用一篇博客来写实在是太长了。阅读起来很不友好,所以我将下面的内容写到另一个博客里,这里附上链接
前言:不敢说这是最全的教程,但这确实是我呕心沥血写的了,如果你认真阅读,可能会发现,我几乎每行代码都写了注释。在哪里用了注解怎么用的,也写了注释帮助大家理解,奈何本人写作水平实在有限,不良之处,还请多多包涵。另外,如果对你有帮助还请点个赞鼓励一下吧哈哈。
第二部分 传送门:https://blog.csdn/qq_44850489/article/details/109309405
综合示例传送门:https://blog.csdn/qq_44850489/article/details/109313589
一,简化开发过程
二,特性快速创建,
直接使用java main 启动内嵌的Tomcat,不需要部署war包
约定starter pom 简化maven配置
依赖maven配置,自动配置spring springmvc
提供程序的健康检查功能
基本不使用xml配置文件,采用注解
三,四大核心
自动配置,自动提供相关配置
起步依赖,告诉springboot需要什么功能,导入依赖
Actuator,深入运行应用程序,差错
命令行界面:可选特性,
四,开发环境
推荐使用 jdk 8 以上
Idea旗舰版自带了 springboot
Eclipse需要安装一个spring boot的插件sts.exe
五,第一个spring boot程序
创建一个springboot项目
使用eclipse sts插件、idea自带插件(需要联网)
使用maven创建
Idea创建过程和其它项目基本一样,点击新建后,选择spring init即可(可自行百度)
加入spring boot的父级和起步依赖
使用插件创建后自动加入父级,起步依赖,所以这步就无需操作
创建springboot的入口main方法
使用插件后也会自动创建好
@SpringBootApplication
public static void main(String[] args){
//启动springboot程序,启动spring容器,如果是web项目,启动内嵌的tomcat
SpringApplication.run(Application.class,args);
}}
创建一个spring mvc的controller
@Controller
public class HelloController {
@RequestMapping("/boot/hello")
public @ResponseBody String hello(){
return "Hello Spring Boot";
}
}
运行spring boot的入口main方法
在页面放访问localhost/boot/hello
至此,第一个springboot程序开发完成
七,第一个springboot程序解析
Springboot的父级依赖配置spring-boot-starter-parent 配置之后,当前的项目就是springboot项目。
Spring-boot-starter-parent是一个特殊的starter依赖,配置之后可以省去其它jar包的version(版本号)配置
Springboot提供了那些 默认依赖,可以查看父级的pom
如果不想要默认版本,可以在pom中写出版本号来覆盖默认版本、
@SpringBootApplication注解是springboot的核心注解,主要作用是开启spring自动配置,因为它要保证在其他注解之前开启,才能保证其他注解被扫描到,所以其它注解要写到和它同级,或者下一级
@Controller 及@ResponseBod依然是我们之前的spring mvc ,因为Spring boot里面依然是 Spring mvc + Spring +MyBatis等框架;
八,springboot的核心配置文件
两种配置文件
.properties文件格式:
键值对的properties属性文件配置方式
.yml文件
格式:
采用一定的空格,换行等格式排版进行配置;
Yml是一种直观的被计算机识别的数据序列化格式,容易被人类阅读,
值与前面的冒号配置项必须要有一个空格;
Yml后缀也可以使用yaml后缀。
九,多配置文件
可以定义多个配置文件.properterties 可以分成 开发配置,上线配置,测试配置
然后可以在 application.properties中激活
激活以后 优先级高于在application中的配置
其它配置的命名规范为 application-**
在application中激活使用哪某个配置文件:dev就是上面的**
spring.profiles.active=dev
十,自定义配置
在springboot的核心配置文件中自定义配置,然后采用注解读取属性值
@value注解,用于读取自定义配置
#自定义配置
name = 中国
age = 6000
@Controller
public class dingyiController {
@Value("${name}")
private String name;
@Value("${age}")
private String age;
@RequestMapping("boot/config")
public @ResponseBody String config(){
return "名字是 "+name +" 年龄是 "+ age;
}
}
第二种方法
boot.name = 弟弟
boot.age = 10
package web.springbootweb01.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Auther: 王海新
* @Date: 2020/8/15 17:35
* @Description:
*/
@Component
@ConfigurationProperties(prefix = "boot")
public class ConfigInfo {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
package web.springbootweb01.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import web.springbootweb01.config.ConfigInfo;
/**
* @Auther: 王海新
* @Date: 2020/8/5 14:53
* @Description:学习自定义配置
*/
@Controller
public class dingyiController {
@Value("${name}")
private String name;
@Value("${age}")
private String age;
@Autowired
private ConfigInfo configInfo;
@RequestMapping("boot/config")
public @ResponseBody String config(){
return "名字是 "+name +" 年龄是 "+ age + "== "+configInfo.getName() +"--"+ configInfo.getAge();
}
}
十二, springboot下的springmvc
@RestController //@RestController = @Controller + @ResponseBody
package web.springbootweb01.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import web.springbootweb01.model.user;
/**
* @Auther: 王海新
* @Date: 2020/8/15 19:43
* @Description:
*/
@RestController //@RestController = @Controller + @ResponseBody
public class MVCController {
@RequestMapping("boot/getUser")
public Object getUser(){
user user = new user();
user.setId(10);
user.setName("天津");
return user;
}
@GetMapping("boot/getUser") // @RequestMapping(value= "boot/getUser", method=RequestMethod.GET )
public Object getUser1(){
user user = new user();
user.setId(10);
user.setName("天津");
return user;
}
}
package web.springbootweb01.model;
/**
* @Auther: 王海新
* @Date: 2020/8/15 19:45
* @Description:
*/
public class user {
private int Id;
private String name;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
十三, springboot下使用jsp
先导入配置(我附上我完整的配置,这样是为了防止只给一部分小白不知道放到哪里),里面有备注,jap的几个配置。同时在中的前3个是指定编译后文件的位置,这个是你在运行后出现404找不到页面时的解决方案。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache/POM/4.0.0" xmlns:xsi="http://www.w3/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache/POM/4.0.0 https://maven.apache/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--继承springboot的父级项目的依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>web</groupId>
<artifactId>springboot-web01</artifactId>
<version>0.0.1</version>
<name>springboot-web01</name>
<description>Demo project for Spring Boot</description>
<!--属性配置-->
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--spring boot开发web项目的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--测试的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入springboot内嵌tomcat对jsp的解析包-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--servlet依赖的jar包start-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!--servlet依赖的jar包start-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!--servlet依赖的jar包start-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!--springboot提供的编译打包插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<!--指定编译java中的xml文件-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<!--指定编译后,将webapp中的文件放入到META-INF/resources-->
<resource>
<directory>src/main/webapp</directory>
<targetPath>
META-INF/resources
</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
</project>
新建一个jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html ; charset=UIF-8">
<title>Insert title here</title>
</head>
<body>
${msg}
</body>
</html>
新建一个controller
package web.springbootweb01.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @Auther: 王海新
* @Date: 2020/8/18 14:17
* @Description:
*/
@Controller
public class JSPController {
@GetMapping("/boot/index")
public String index(Model model){
model.addAttribute("msg", "spring boot 集成 jsp.");
return "index";
}
}
效果
十四,springboot继承mybatis
我在重新创建一个项目来演示这个:这个我是用的maven创建的,当然你也可以用上面的方法创建
目录如下(有一部分是代码生成时生成的,就是mybatis的自动生成,马上讲到)
创建好后,我们要导入配置
在pom.xml中
1.首先要做的就是继承springboot的父级依赖,继承了父级依赖才算是一个springboot项目
2.然后属性配置,可有可无,主要是看用到用不到,这里我们直接配置上
3.开发web的起步依赖还有测试依赖一样都装上
4.然后就是mabatis 和jdbc驱动包的依赖(重点了)
5.然后我们在配置上代码自动生成,因为我就放在了根目录下,所以位置直接是文件名
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache/POM/4.0.0"
xmlns:xsi="http://www.w3/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache/POM/4.0.0 http://maven.apache/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wanghaixin.springboot</groupId>
<artifactId>03-springboot-mabatis</artifactId>
<version>1.0.0</version>
<!--继承springboot的父级项目的依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--属性配置-->
<properties>
<project.build.sourceRncoding>UTF-8</project.build.sourceRncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--spring boot开发web项目的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--测试的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--加载mabatis整合springboot-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--MySQL的hdbc驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!--mybatis代码自动生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
Ok下面创建一个application.properties文件
这里面的东西是连接数据库的,你要改成你的数据库名字 密码 地址
mybatis.mapper-locations=classpath:com/wanghaixin/springboot/mapper/*.xml
#配置数据库连接
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.rul=jdbc:mysql://localhost:3306/springdb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8$useSSL=false
重点(GeneratorMapper.xml)这个就是管自动生成的文件了。小编感觉很神奇(第一次接触),我是重网上copy下来,然后改动里面需要自己设置一下。赶紧copy到你电脑里一起来改动吧。
改动位置:
JDBC驱动包所在位置你电脑上的位置
配置数据库连接信息 我的数据库是本地的,springdb
然后下面三个配置想,com.wanghaixin.springboot. (王海新就是我的名字了) 是我项目的路径,上面附上了我的目录可以看出来,
4.最后数据库表名。。。
Student就是我的表名了,注意第二个首字母大写。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 指定连接数据库的JDBC驱动包所在位置,指定到你本机的完整路径 -->
<classPathEntry location="D:/develop/bao/mysql-connector-java-8.0.15/mysql-connector-java-8.0.15.jar"/>
<!-- 配置table表信息内容体,targetRuntime指定采用MyBatis3的版本 -->
<context id="tables" targetRuntime="MyBatis3">
<!--序列化-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!--以下需要插件 -->
<!--
插入成功后返回ID
<plugin type="cn.doitymon.generator.plugin.InsertAndReturnKeyPlugin"/>
分页查询功能
<plugin type="cn.doitymon.generator.plugin.SelectByPagePlugin"/>
生成带有for update后缀的select语句插件
<plugin type="cn.doitymon.generator.plugin.SelectForUpdatePlugin"/> -->
<!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/springdb?serverTimezone=GMT"
userId="root"
password="123456">
</jdbcConnection>
<!-- 生成model类,targetPackage指定model类的包名, targetProject指定生成的model放在eclipse的哪个工程下面-->
<javaModelGenerator targetPackage="com.wanghaixin.springboot.model" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名, targetProject指定生成的mapper.xml放在eclipse的哪个工程下面 -->
<sqlMapGenerator targetPackage="com.wanghaixin.springboot.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名, targetProject指定生成的Mapper接口放在eclipse的哪个工程下面 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.wanghaixin.springboot.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 数据库表名及对应的Java模型类名 -->
<table tableName="student"
domainObjectName="Student"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
OK搞完这些,就要你去创建一下数据库了,这里不再带着你弄了,上劲暴的。现在你还没有真正敲代码吧,假设你已经创建好了,直接点击idea右边的maven
然后控制台出现 BUILD SUCCESS就是成功了,再看你的项目已经自动生成好多东西了哈哈哈。
当然我在这里是卡了一下壳,我是根据控制台报的错误,知道一个是时区问题,还有一个什么我不记得了(晚上攻破这座城的,弄完就睡了)。不过有问题就看这个控制台的提示解决一下吧。我的代码肯定已经解决这两个问题啦。
现在我们来完成一个业务,查询所有数据
先建立好上级目录, 上图忘了标注,在springboot下创建Application启动类
package com.wanghaixin.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:49
* @Description:
*/
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
上图忘了标注,在controller中也要创建
我们只是演示mabatis 所以直接返回json数据,用@ResController注解 @getMapping绑定路径 @Autowired来扫描上数据
package com.wanghaixin.springboot.controller;
import com.wanghaixin.springboot.model.Student;
import com.wanghaixin.springboot.service.StudentSertvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:52
* @Description:
*/
@RestController
public class MyBatisController {
@Autowired
private StudentSertvice studentSertvice;
@GetMapping("/boot/students")
public Object students(){
return studentSertvice.getAllStuent();
}
}
然后创建StudentSertvice 这个是一个接口 里面规范 一个规范一个返回所有数据的方法。
package com.wanghaixin.springboot.service;
import com.wanghaixin.springboot.model.Student;
import java.util.List;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:55
* @Description:
*/
public interface StudentSertvice {
public List<Student> getAllStuent();
}
然后在impl中建立StudentSertviceImpl 继承接口,实现这个方法,返回Mapper中的数据
利用@Service标注,@Autowired扫描mapper中获得的数据
package com.wanghaixin.springboot.service.impl;
import com.wanghaixin.springboot.mapper.StudentMapper;
import com.wanghaixin.springboot.model.Student;
import com.wanghaixin.springboot.service.StudentSertvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:56
* @Description:
*/
@Service
public class StudentSertviceImpl implements StudentSertvice {
@Autowired
private StudentMapper studentMapper;
@Override
public List<Student> getAllStuent() {
return studentMapper.selectAllStudent();
}
}
打开mapper中自动生成的代码,如下如,(这里我本来只有两个抽象方法来着,不知道为什么,后来看着别人的都手动写上去了,如果你知道,可以教教我哈)
在service中我们返回了 return studentMapper.selectAllStudent(); 但是没有这个方法,这个是一定需要我们手动去创建的。
package com.wanghaixin.springboot.mapper;
import com.wanghaixin.springboot.model.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface StudentMapper {
int deleteByPrimaryKey(Integer io);
int insert(Student record);
int insertSelective(Student record);
Student selectByRrimaryKey(Integer id);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
List<Student> selectAllStudent();
}
然后再同目录里的.xml中
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis//DTD Mapper 3.0//EN" "http://mybatis/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wanghaixin.springboot.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.wanghaixin.springboot.model.Student">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
<sql id="Base_Column_List">
id,name, age
</sql>
<!--查询所有学生-->
<select id="selectAllStudent" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
</select>
<insert id="insert" parameterType="com.wanghaixin.springboot.model.Student">
insert into student (id, name, age
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
)
</insert>
<insert id="insertSelective" parameterType="com.wanghaixin.springboot.model.Student">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<resultMap id="BaseResultMap" type="com.wanghaixin.springboot.model.Student">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
<insert id="insert" parameterType="com.wanghaixin.springboot.model.Student">
insert into student (id, name, age
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
)
</insert>
<insert id="insertSelective" parameterType="com.wanghaixin.springboot.model.Student">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
</mapper>
上面是完整的,我们只写,这个sql应该就是代表所有的列名 然后下main查询方法,id就是mapper中的方法名 返回值就是BaseResultMap 这个好像都是这样返回,没有关系
<sql id="Base_Column_List">
id,name, age
</sql>
<!--查询所有学生-->
<select id="selectAllStudent" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
</select>
完整的 在controller层
package com.wanghaixin.springboot.controller;
import com.wanghaixin.springboot.service.StudentSertvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:52
* @Description:
*/
//添加注解,RestController注解,表名这个是一个controller
@RestController
public class MyBatisController {
//这个Autowired注解,可以将StudentSertvice 对象中返回的数据自动封装到这里
@Autowired
private StudentSertvice studentSertvice;
@GetMapping("/boot/students")
public Object students(){
//这里直接返回数据,就会返回对象中的数据,以json数据格式返回
return studentSertvice.getAllStuent();
}
}
那我们看看server层如何编写
首先创建接口,
package com.wanghaixin.springboot.service;
import com.wanghaixin.springboot.model.Student;
import java.util.List;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:55
* @Description:
*/
public interface StudentSertvice {
public List<Student> getAllStuent();
}
然后再创建实现类,实现里面的方法
package com.wanghaixin.springboot.service.impl;
import com.wanghaixin.springboot.mapper.StudentMapper;
import com.wanghaixin.springboot.model.Student;
import com.wanghaixin.springboot.service.StudentSertvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:56
* @Description:
*/
//在方法上添加service注解
@Service
public class StudentSertviceImpl implements StudentSertvice {
//同时添加自动注入注解,将返回的数据已json返回回来
@Autowired
private StudentMapper studentMapper;
//实现接口中的方法
@Override
public List<Student> getAllStuent() {
return studentMapper.selectAllStudent();
}
}
下面就是mapper层了,先定义接口(这些都是在代码生成的时候创建好的,但是我们上面写的一个调用所有数据的selectAllstudent需要我们在这里面写出来)
package com.wanghaixin.springboot.mapper;
import com.wanghaixin.springboot.model.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
//这里添加了Mapper注解,这个注解如果在启动方法上添加了@MapperScan(*com.bjpowernode.springboot.mapper") 自动扫描注解,那就不用再在每一个mapper上添加注解了
@Mapper
public interface StudentMapper {
int insert(Student record);
int insertSelective(Student record);
//上面两个方法时我用自动代码生成时,出现的,那现在我们要完后的是下面这个自定义的方法,要手动写上拉。
List<Student> selectAllStudent();
}
然后再在同目录下的.xml文件中,写出这个方法对应的sql语句。
我在这里把我的整个.xml文件贴出来了,会标注上哪个是用于这个方法自己建立的。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis//DTD Mapper 3.0//EN" "http://mybatis/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wanghaixin.springboot.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.wanghaixin.springboot.model.Student">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
//这个sql和下面的查询所有学生一起完成数据查询
<sql id="Base_Column_List">
id , name , age
</sql>
<!--查询所有学生-->
<select id="selectAllStudent" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
</select>
<insert id="insert" parameterType="com.wanghaixin.springboot.model.Student">
insert into student (id, name, age
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
)
</insert>
<insert id="insertSelective" parameterType="com.wanghaixin.springboot.model.Student">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
</mapper>
写到这里,就可以点击运行吧整个数据库里面的数据已json数据的形式打印出来了。但是我在这个过程中出现了很多问题。配置方面呀,书写方面呀等等,甚至重启了一下电脑 报出来的错误就没有了,至于你会不会遇到,我也不得而知。我粘贴出来的在我这里确实可以运行,但是不要放弃,认真百度解决。我粘贴上我的成果图
十五,SpringBoot下事务配置管理
1.在入口类中使用注解: @EnableTransactionManagement 开启事务支持
2.访问数据库的Service方法上添加注解 @Transactional即可;
配置事务还是在上面的项目里演示:
启动类上加注解
package com.wanghaixin.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:49
* @Description:
*/
@SpringBootApplication
@MapperScan(basePackages = "com.wanghaixin.springboot.mapper")
@EnableTransactionManagement //开始事务支持
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
controller层创建这个一个方法
@GetMapping("/boot/update")
public Object update(){
return studentSertvice.update();
}
service层 同样创建
package com.wanghaixin.springboot.service;
import com.wanghaixin.springboot.model.Student;
import java.util.List;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:55
* @Description:
*/
public interface StudentSertvice {
public List<Student> getAllStuent();
public Object update();
}
在这个service上要添加注解@Transactional 来标注这个方法要开启事务
package com.wanghaixin.springboot.service.impl;
import com.wanghaixin.springboot.mapper.StudentMapper;
import com.wanghaixin.springboot.model.Student;
import com.wanghaixin.springboot.service.StudentSertvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Auther: 王海新
* @Date: 2020/8/19 16:56
* @Description:
*/
@Service
public class StudentSertviceImpl implements StudentSertvice {
@Autowired
private StudentMapper studentMapper;
@Override
public List<Student> getAllStuent() {
return studentMapper.selectAllStudent();
}
//开启事务
@Transactional
@Override
public Object update(){
Student student = new Student();
student.setName("李四——");
student.setAge(18);
int update = studentMapper.insert(student);
System.out.println("更新结果: " + update);
//除数不能为零,所以此处会抛出一个运行时异常,上一步的更新就会回滚
int a = 10/0;
return null;
}
}
用10/0抛出异常,打开事务,和关闭事务来看看数据会不会i被写到数据库里
十六,Springboot实现RestFull
RestFull是一种互联网软件架构设计风格,基于这种风格设计的接口更简洁,更有层次。
如图所示,就是将url后面的参数改变一下格式。
我用开篇时建立的那个项目给大家做演示,
非常简单那,一个@PathVariable注解就可以实现
直接在controlled层
package web.springbootweb01.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import web.springbootweb01.model.user;
/**
* @Auther: 王海新
* @Date: 2020/9/22 13:48
* @Description:
*/
@RestController
public class RESTFullController {
@RequestMapping("/boot/user/{id}")
public Object user(@PathVariable("id") Integer id){
user user = new user();
user.setId(id);
user.setName("张山");
return user;
}
@RequestMapping("/boot/user/{id}/{name}")
public Object user(@PathVariable("id") Integer id , @PathVariable("name") String name ){
user user = new user();
user.setId(id);
user.setName(name);
return user;
}
}
下面时我的效果图
另外有这些情况
@RequestMapping("/boot/user/{id}/{name}")
public Object user(@PathVariable("id") Integer id , @PathVariable("name") String name ){
user user = new user();
user.setId(id);
user.setName(name);
return user;
}
//下面这个方法 和上面这个方法的参数个数相同,类型也相同在运行的时候就会报错
@RequestMapping("/boot/user/{name}/{id}")
public Object user1(@PathVariable("id") Integer id , @PathVariable("name") String name ){
user user = new user();
user.setId(id);
user.setName(name);
return user;
}
//这个参数的位置 可以加到任何的地方,
@RequestMapping("/boot/{name}/user")
public Object user1( @PathVariable("name") String name ){
user user = new user();
user.setName(name);
return user;
}
这个错误就是因为参数相同,但在controller中却有两个方法接受,所以报错
十七,SpringBoot的热部署插件
这个热部署插件时spring boot自己开发出来的,就是一个jar包,我们在使用的时候导入即可。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
导入后要重新启动一下。如果使用的时eclipse ,那么每次改动完成之后他都会自动给你编译。如果是idea 就需要点击一下build -》build Model。。 才可以自动编译。
另外还有可能会有一些小问题,就是明明点击了但是没有生效,这个时候就要我们手动重启一下
下面更新 redis
十八,因为用一篇博客来写实在是太长了。阅读起来很不友好,所以我将下面的内容写到另一个博客里,这里附上链接
传送门:
本文标签: 完整版详解实例代码SpringBoot
版权声明:本文标题:SpringBoot实例加每行代码详解,完整版。从0到1! 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1726162518a1057876.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论