Spring boot查询对数据库增删查改实例

参考教程:http://www.imooc.com/learn/767\

SpringBoot

这里写图片描述

SpringBoot 是 SpringMVC 的升级版,相对于编码、配置、部署和监控方面,会更加简单

微服务

微服务是一个新兴的软件架构,就是把一个大型的单个应用程序和服务拆分为数十个的支持微服务。一个微服务的策略可以让工作变得更为简便,它可扩展单个组件而不是整个的应用程序堆栈,从而满足服务等级协议。

Spring 为 微服务提供了一整套的组件-SpringClound , SpirngBoot 就是该基础。

这里写图片描述

第一个SpringBoot程序

这里使用的开发软件是IntelliJ Idea,和Eclipse差不太多,界面更炫酷,功能更强大;Android Studio就是基于IntelliJ 开发的,我之前使用过Android Studio,它俩界面几乎一样。

IntelliJ Idea官网:http://www.jetbrains.com/idea/ 
配置好 maven, tomcat, jdk 就可以使用了

maven配置的中央仓库阿里云镜像

这个地址下载 jar 包的速度,谁用谁知道!

setting.xml


 
 
  1. .
  2. .
  3. <mirrors>
  4. <mirror>
  5. <id>alimaven </id>
  6. <name>aliyun maven </name>
  7. <url>http://maven.aliyun.com/nexus/content/groups/public/ </url>
  8. <mirrorOf>central </mirrorOf>
  9. </mirror>
  10. </mirrors>
  11. .
  12. .
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

使用IDEA创建SpringBoot项目

我的IDEA版本:IntelliJ IDEA 2016.3.1

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

项目结构为:

这里写图片描述

项目默认的 maven pom.xml文件

pom.xml


 
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
  4. <modelVersion>4.0.0 </modelVersion>
  5. <groupId>com.jxust </groupId>
  6. <artifactId>spirngbootdemo </artifactId>
  7. <version>0.0.1-SNAPSHOT </version>
  8. <packaging>jar </packaging>
  9. <name>spirngbootdemo </name>
  10. <description>Demo project for Spring Boot </description>
  11. <parent>
  12. <groupId>org.springframework.boot </groupId>
  13. <artifactId>spring-boot-starter-parent </artifactId>
  14. <version>1.4.2.RELEASE </version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8 </project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8 </project.reporting.outputEncoding>
  20. <java.version>1.8 </java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot </groupId>
  25. <artifactId>spring-boot-starter-web </artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot </groupId>
  29. <artifactId>spring-boot-starter-test </artifactId>
  30. <scope>test </scope>
  31. </dependency>
  32. </dependencies>
  33. <build>
  34. <plugins>
  35. <plugin>
  36. <groupId>org.springframework.boot </groupId>
  37. <artifactId>spring-boot-maven-plugin </artifactId>
  38. </plugin>
  39. </plugins>
  40. </build>
  41. </project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

运行SpirngbootdemoApplication的main方法,就能开始运行。

其他启动方式,请看视频教程http://www.imooc.com/learn/767\

控制台输出:


 
 
  1. "C: \Program Files \Java \jdk 1.8.0_91 \bin \java " ....
  2. . ___ _ _ _ _ _ _
  3. / \\ / __ _ '_ __ _ _(_)_ __ __ _ \ \ \ \
  4. ( ( ) \_ __ | ' _ | '_| | '_ \/ _` | \ \ \ \
  5. \\/ __ _) | | _) | | | | | | | (_| | ) ) ) )
  6. ' |___ _ | .__| _ | | _ |_| |_ \_ _, | / / / /
  7. ========= |_|============== |___/=/_/_/_/
  8. :: Spring Boot :: (v1.4.2.RELEASE)
  9. 2016-12-16 14:56:52.083 INFO 15872 --- [ main ] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
  10. 2016-12-16 14:56:52.215 INFO 15872 --- [ main ] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
  11. 2016-12-16 14:56:52.255 INFO 15872 --- [ main ] com.jxust.SpirngbootdemoApplication : Started SpirngbootdemoApplication in 7.795 seconds (JVM running for 9.177)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

从这里可以看到 Tomcat 的端口号,因为还没有自定义Controller,所以还没有视图,下面来创建一个输出Hello SpringBoot!的视图。

创建一个HelloController,位于controller包下

这里写图片描述

HelloController.java


 
 
  1. package com.jxust.controller;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. /**
  5. * Created by Peng
  6. * Time: 2016/12/16 15:45
  7. */
  8. @RestController
  9. public class HelloController {
  10. @RequestMapping( "/hello")
  11. public String say (){
  12. return "Hello SpringBoot!";
  13. }
  14. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

@RestController Spring4 之后新加的注解,原来返回json需要@ResponseBody配合@Controller,现在一个顶俩

在浏览器中输入http://localhost:8080/hello就能输出Hello SpringBoot!这句话。

这里写图片描述

自定义属性配置

用到的是application.properties这个文件

这里写图片描述

配置端口号和访问前缀

application.properties


 
 
  1. server.port= 8081
  2. server.context-path=/springboot
  • 1
  • 2

这里写图片描述

除了使用.properties格式的文件,还可以使用.yml格式的配置文件(推荐),更加简便 
application.yml 
这里写图片描述

把原来的application.properties文件删除 
注意格式,空格不能少

获取配置文件中的属性值

我们也可以在配置文件中,配置数据,在 Controller 中获取,比如: 
application.yml


 
 
  1. server:
  2. port: 8081
  3. context-path: /springboot
  4. name: 小胖
  • 1
  • 2
  • 3
  • 4

HelloController 获取配置文件中的值

HelloController.java


 
 
  1. ....
  2. @RestController
  3. public class HelloController {
  4. @Value( "${name}")
  5. private String name;
  6. @RequestMapping(value = "/hello",method = RequestMethod.GET)
  7. public String say (){
  8. return name;
  9. }
  10. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

返回的为name的值

这里写图片描述

配置文件中值配置方式的多样化

配置文件的值可以是多个,也可以是组合,如:

  • application.yml

 
 
  1. name: 小胖
  2. age: 22
  • 1
  • 2

或者

  • application.yml

 
 
  1. name: 小胖
  2. age: 22
  3. content: "name: ${name},age: ${age}"
  • 1
  • 2
  • 3

或者

  • application.yml

 
 
  1. server:
  2. port: 8081
  3. context-path: /springboot
  4. person:
  5. name: 小胖
  6. age: 22
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

前两种配置获取值的方式都是一样的,但是对于这种方式,person 有相应的两个属性,需要这样处理

PersonProperties.java


 
 
  1. package com.jxust;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.stereotype.Component;
  4. /**
  5. * Created by Peng
  6. * Time: 2016/12/16 16:34
  7. */
  8. @Component
  9. @ConfigurationProperties(prefix = "person")
  10. public class PersonProperties {
  11. private String name;
  12. private Integer age;
  13. public String getName () {
  14. return name;
  15. }
  16. public void setName (String name) {
  17. this.name = name;
  18. }
  19. public Integer getAge () {
  20. return age;
  21. }
  22. public void setAge (Integer age) {
  23. this.age = age;
  24. }
  25. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

Alt+insert快捷键提示生成 Getter and Setter

pom.xml需要加入下面的依赖,处理警告


 
 
  1. <dependency>
  2. <groupId>org.springframework.boot </groupId>
  3. <artifactId>spring-boot-configuration-processor </artifactId>
  4. <optional>true </optional>
  5. </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

HelloController.java


 
 
  1. package com.jxust.controller;
  2. import com.jxust.PersonProperties;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestMethod;
  6. import org.springframework.web.bind.annotation.RestController;
  7. /**
  8. * Created by Peng
  9. * Time: 2016/12/15 20:55
  10. */
  11. @RestController
  12. public class HelloController {
  13. @Autowired
  14. private PersonProperties personProperties;
  15. @RequestMapping(value = "/hello",method = RequestMethod.GET)
  16. public String say (){
  17. return personProperties.getName()+personProperties.getAge();
  18. }
  19. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

这里写图片描述

关于配置文件application.yml的多套配置

类似 il8n 文件国际化的配置方式i18n_en_US.propertiesi18n_zh_CN.properties 
这样能解决,需要频繁修改配置的尴尬

这里写图片描述

application.yml配置文件决定使用那套配置文件。

application.yml


 
 
  1. spring:
  2. profiles:
  3. active: a
  • 1
  • 2
  • 3

application-a.yml


 
 
  1. server:
  2. port: 8081
  3. context-path: /springboot
  4. person:
  5. name: 小雷
  6. age: 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

application-b.yml


 
 
  1. server:
  2. port: 8081
  3. context-path: /springboot
  4. person:
  5. name: 小胖
  6. age: 22
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

SpringBoot增删改查实例

完整的项目结构

这里写图片描述

Controller的使用


 
 
  1. @Controller chu处理http请求
  2. @RestController Spring4 之后新加的注解,原来返回json需要 @ResponseBody配合 @Controller
  3. @RequestMapping 配置url映射
  • 1
  • 2
  • 3
  • 4
  • 5

对于 REST 风格的请求 
这里写图片描述

对于 Controller 中的方法上的注解


 
 
  1. @RequestMapping(value = "/hello",method = RequestMethod.GET)
  2. @RequestMapping(value = "/hello",method = RequestMethod.POST)
  3. @RequestMapping(value = "/hello",method = RequestMethod.DELETE)
  4. @RequestMapping(value = "/hello",method = RequestMethod.PUT)
  • 1
  • 2
  • 3
  • 4

SpringBoot 对上面的注解进行了简化


 
 
  1. @GetMapping(value = "/girls")
  2. @PostMapping(value = "/girls")
  3. @PutMapping(value = "/girls/{id}")
  4. @DeleteMapping(value = "/girls/{id}")
  • 1
  • 2
  • 3
  • 4

浏览器需要发送不同方式的请求,可以安装HttpRequester插件,火狐浏览器可以直接搜索该组件安装。

这里写图片描述

这里写图片描述

spring-data-jpa

JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

Hibernate3.2+TopLink 10.1.3以及OpenJPA都提供了JPA的实现。

利用JPA创建MySQL数据库

pom.xml加入JPAMySQL的依赖


 
 
  1. <dependency>
  2. <groupId>org.springframework.boot </groupId>
  3. <artifactId>spring-boot-starter-data-jpa </artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>mysql </groupId>
  7. <artifactId>mysql-connector-java </artifactId>
  8. </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

配置JPA和数据库

application.yml


 
 
  1. spring:
  2. profiles:
  3. active: a
  4. datasource:
  5. driver -class -name : com . mysql . jdbc . Driver
  6. url: jdbc:mysql: //127.0.0.1:3306/db_person
  7. username: root
  8. password: root
  9. jpa:
  10. hibernate:
  11. ddl -auto: update
  12. show -sql: true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

格式很重要 
需要自己手动去创建 db_person 数据库

创建与数据表对应的实体类Person

这里写图片描述

Person.java


 
 
  1. package com.jxust.entity;
  2. import javax.persistence.Entity;
  3. import javax.persistence.GeneratedValue;
  4. import javax.persistence.Id;
  5. /**
  6. * Created by Peng
  7. * Time: 2016/12/16 17:56
  8. */
  9. @Entity
  10. public class Person {
  11. @Id
  12. @GeneratedValue
  13. private Integer id;
  14. private String name;
  15. private Integer age;
  16. //必须要有构造函数
  17. public Person () {
  18. }
  19. public Integer getId () {
  20. return id;
  21. }
  22. public void setId (Integer id) {
  23. this.id = id;
  24. }
  25. public String getName () {
  26. return name;
  27. }
  28. public void setName (String name) {
  29. this.name = name;
  30. }
  31. public Integer getAge () {
  32. return age;
  33. }
  34. public void setAge (Integer age) {
  35. this.age = age;
  36. }
  37. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

运行项目后,查看数据库,会自动创建表 person


 
 
  1. mysql> use db_person;
  2. Database changed
  3. mysql> desc person;
  4. + -------+--------------+------+-----+---------+----------------+
  5. | Field | Type | Null | Key | Default | Extra |
  6. + -------+--------------+------+-----+---------+----------------+
  7. | id | int(11) | NO | PRI | NULL | auto_increment |
  8. | age | int(11) | YES | | NULL | |
  9. | name | varchar(255) | YES | | NULL | |
  10. + -------+--------------+------+-----+---------+----------------+
  11. 3 rows in set (0.09 sec)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

接下来就可以进行person表的增删改查了

创建控制器PersonController.java

这里写图片描述

首先创建一个接口PersonRepository,位于dao包下,PersonController调用该接口继承自JpaRepository的方法,来实现和数据库交互

这个PersonRepository接口的功能,与SSM框架中 dao 层接口功能有异曲同工之妙;在SSM框架中,Service层通过该接口,间接执行Mybatis数据库映射文件(.xml)里的相应sql语句,执行数据库增删改查的操作。(Mapper自动实现DAO接口)

PersonRepository.java


 
 
  1. package com.jxust.dao;
  2. import com.jxust.entity.Person;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. /**
  5. * Created by Peng
  6. * Time: 2016/12/16 18:07
  7. */
  8. public interface PersonRepository extends JpaRepository<Person,Integer> {
  9. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

PersonController.java


 
 
  1. package com .jxust .controller ;
  2. import com .jxust .dao .PersonRepository ;
  3. import com .jxust .entity .Person ;
  4. import org .springframework .beans .factory .annotation .Autowired ;
  5. import org .springframework .web .bind .annotation .GetMapping ;
  6. import org .springframework .web .bind .annotation .RestController ;
  7. import java .util .List ;
  8. /**
  9. * Created by Peng
  10. * Time: 2016/12/16 18:04
  11. */
  12. @ RestController
  13. public class PersonController {
  14. @ Autowired
  15. PersonRepository personRepository ;
  16. @ GetMapping( value = "/person")
  17. private List<Person> personList() {
  18. return personRepository .findAll() ;
  19. }
  20. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

在数据库中添加两条数据


 
 
  1. mysql> select * from person;
  2. +----+------+--------+
  3. | id | age | name |
  4. +----+------+--------+
  5. | 1 | 23 | 夏洛 |
  6. | 2 | 21 | 马冬梅 |
  7. +----+------+--------+
  8. 2 rows in set ( 0. 04 sec)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

启动项目执行请求http://localhost:8081/springboot/person

这里写图片描述

控制台输出的sql语句:

Hibernate: select person0_.id as id1_0_, person0_.age as age2_0_, person0_.name as name3_0_ from person person0_
 
 
  • 1

其他增删改查的方法

PersonController.java


 
 
  1. ....
  2. /**
  3. * 添加一个人员
  4. *
  5. * @param name
  6. * @param age
  7. * @return
  8. */
  9. @PostMapping(value = "/person")
  10. public Person personAdd (@ RequestParam ("name") String name,
  11. @ RequestParam ("age") Integer age) {
  12. Person person = new Person();
  13. person.setName(name);
  14. person.setAge(age);
  15. return personRepository.save(person);
  16. }
  17. /**
  18. * 查询一个人员
  19. *
  20. * @param id
  21. * @return
  22. */
  23. @GetMapping(value = "/person/{id}")
  24. public Person personFindOne (@ PathVariable ("id") Integer id) {
  25. return personRepository.findOne(id);
  26. }
  27. /**
  28. * 删除一个人员
  29. *
  30. * @param id
  31. */
  32. @DeleteMapping(value = "/person/{id}")
  33. public void personDelete (@ PathVariable ("id") Integer id) {
  34. personRepository.delete(id);
  35. }
  36. /**
  37. * 更新一个人员
  38. *
  39. * @param id
  40. * @param name
  41. * @param age
  42. * @return
  43. */
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值