总体思路:先写dao,再写service

1.http://start.spring.io

生成对应的模板

SpringBoot学习笔记插图

2.写TestCotroller类,类上写@RestCotroller注解

3.TestCotroller类里写方法,方法上写@GetMapping(“/方法名”)注解

SpringBoot学习笔记插图(1)

4.不一定要写GetMapping,具体看做什么操作

SpringBoot学习笔记插图(2)

5.服务跑起来,试试效果

SpringBoot学习笔记插图(3)

6.安装MySQL数据库,网上很多资料,可以参考http://www.cnblogs.com/zhangkanghui/p/9613844.html

7.建立测试库

CREATE DATABASE test CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

SpringBoot学习笔记插图(4)

8.建表

CREATE TABLE student( id int AUTO_INCREMENT PRIMARY KEY,name VARCHAR(50) NOT NULL,email VARCHAR(100) NOT NULL,age int );

SpringBoot学习笔记插图(5)

9.返回IDEA,写dao层,dao层都是接口,负责与数据库的交互。加上注解@Restpository

注解作用:告诉SpringBoot框架,这是Repository层的代码。底层原理是依赖注入,将代码加入容器中,让框架能扫描到。

实现要继承JpaRepository,因为父类JpaRepository几乎包含了对数据库的增删查改。

SpringBoot学习笔记插图(6)

10.在dao层中建一个student类,这个类用来映射数据库中的student表。

注解:

@Entity

@Table(name=”student”)

告诉SpringBoot框架这个类用来映射数据库中的student表。

注解:

@Id,告诉SpringBoot框架,它是一个自增的主键。

@Colum(name=”age”),写在字段头上,告诉SpringBoot框架,java中的字段对应数据库中哪个字段。如果相同可以不写。

@GeneratedValue(strategy=”IDENTITY”),写在字段头,告诉SpringBoot框架,id字段是数据库自增的字段。

SpringBoot学习笔记插图(7)

如果不知道注解的参数,可以按住crtl键,鼠标左键进去看。

10.返回去写StudentRepository接口,给父类的泛类型添上值。

SpringBoot学习笔记插图(8)

11.开始写service层

面向接口编程,先写接口,再写实现。

注解:@Service在实现层,让SpringBoot框架来注入。

@Override:告诉SpringBoot的框架,这个方法是实现接口的。(自动带出)

声明StudentRepository接口,使用@AutoWired注入

@Autowired:告诉SpringBoot框架,StudentRepository接口被注入到实现类中。

SpringBoot学习笔记插图(9)

12.开始写Controller层的代码。

注入@RestController,告诉SpringBoot框架这个是Controller层。

因为是查询,所以再注入@GetMapping。

@PathVariable:对应路径变量。

@Autowired代表:注入Service层的代码

总结,可以看到,咱们先写了dao层,然后写service层的时候,使用了这个注解@Autowired,这是把dao层的代码注入进Service层,然后Controller层也写了这个注解@Autowired,这就是Service层的代码又注入到Controller层。

SpringBoot学习笔记插图(10)

SpringBoot学习笔记插图(11)

13.配置数据库url

SpringBoot学习笔记插图(12)

14.手工插数据进mysql数据库

SpringBoot学习笔记插图(13)

15.启动项目,网页输出json

SpringBoot学习笔记插图(14)

SpringBoot学习笔记插图(15)

本站无任何商业行为
个人在线分享 » SpringBoot学习笔记
E-->