最近在学习SpringBoot,用的IDEA进行开发,这个算是入门学习笔记二,希望我这个新手写的个人心得见解能够帮助到你们!
前提:
- 有看过我之前写的入门学习笔记一即可
- 项目源码分享:https://github.com/xiaoaibin/springboot-demo-girl.git
好的, 我们接着之前的项目继续开始学习:
1.SpringBoot项目启动的方式,之前我们使用了最常见的一种,但是还有其他的启动方式:
- 第一种方式,直接执行项目生成的GirlApplication类的main方法;
- 第二种方式,进入到项目所在目录文件夹,执行 mvn spring-boot:run 命令,如下图:
Microsoft Windows [版本 10.0.14393] (c) 2016 Microsoft Corporation。保留所有权利。 C:\Users\aibin>d: D:\>cd D:\InputProjects\learn_project\girl D:\InputProjects\learn_project\girl>mvn spring-boot:run [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building girl 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] >>> spring-boot-maven-plugin:1.5.3.RELEASE:run (default-cli) > test-compile @ girl >>> [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ girl --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 3 resources [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ girl --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 7 source files to D:\InputProjects\learn_project\girl\target\classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ girl --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 1 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ girl --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] <<< spring-boot-maven-plugin:1.5.3.RELEASE:run (default-cli) < test-compile @ girl <<< [INFO] [INFO] --- spring-boot-maven-plugin:1.5.3.RELEASE:run (default-cli) @ girl --- . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.3.RELEASE) 2017-06-07 12:22:24.858 INFO 21932 --- [ main] com.aibinxiao.GirlApplication : Starting GirlApplication on XiaoAibin with PID 21932 (D:\InputProjects\learn_project\girl\target\classes started by aibin in D:\InputProjects\learn_project\girl) 2017-06-07 12:22:24.876 INFO 21932 --- [ main] com.aibinxiao.GirlApplication : The following profiles are active: dev 2017-06-07 12:22:24.939 INFO 21932 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f8d0f26: startup date [Wed Jun 07 12:22:24 GMT+08:00 2017]; root of context hierarchy 2017-06-07 12:22:26.568 INFO 21932 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8081 (http) 2017-06-07 12:22:26.581 INFO 21932 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat 2017-06-07 12:22:26.582 INFO 21932 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.14 2017-06-07 12:22:26.667 INFO 21932 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/girl] : Initializing Spring embedded WebApplicationContext 2017-06-07 12:22:26.668 INFO 21932 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1735 ms 2017-06-07 12:22:26.819 INFO 21932 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2017-06-07 12:22:26.824 INFO 21932 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2017-06-07 12:22:26.824 INFO 21932 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2017-06-07 12:22:26.825 INFO 21932 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2017-06-07 12:22:26.826 INFO 21932 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2017-06-07 12:22:27.360 INFO 21932 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 2017-06-07 12:22:27.377 INFO 21932 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: default ...] 2017-06-07 12:22:27.442 INFO 21932 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final} 2017-06-07 12:22:27.443 INFO 21932 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 2017-06-07 12:22:27.446 INFO 21932 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist 2017-06-07 12:22:27.483 INFO 21932 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 2017-06-07 12:22:27.584 INFO 21932 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect 2017-06-07 12:22:27.904 INFO 21932 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update 2017-06-07 12:22:28.007 INFO 21932 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2017-06-07 12:22:28.674 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f8d0f26: startup date [Wed Jun 07 12:22:24 GMT+08:00 2017]; root of context hierarchy 2017-06-07 12:22:28.762 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/girls],methods=[GET]}" onto public java.util.List<com.aibinxiao.Girl> com.aibinxiao.GirlController.girlList() 2017-06-07 12:22:28.763 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/addgirl],methods=[POST]}" onto public java.lang.String com.aibinxiao.GirlController.addGirl(java.lang.String,java.lang.Integer) 2017-06-07 12:22:28.765 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/update/{id}],methods=[PUT]}" onto public com.aibinxiao.Girl com.aibinxiao.GirlController.updateGirl(java.lang.Integer,java.lang.String,java.lang.Integer) 2017-06-07 12:22:28.767 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/delete/{id}],methods=[DELETE]}" onto public void com.aibinxiao.GirlController.deleteGirl(java.lang.Integer) 2017-06-07 12:22:28.768 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/insettwo],methods=[POST]}" onto public void com.aibinxiao.GirlController.insertTwoGirl() 2017-06-07 12:22:28.769 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/findbyage/{age}],methods=[GET]}" onto public java.util.List<com.aibinxiao.Girl> com.aibinxiao.GirlController.findByAge(java.lang.Integer) 2017-06-07 12:22:28.769 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getone/{id}],methods=[GET]}" onto public com.aibinxiao.Girl com.aibinxiao.GirlController.findOne(java.lang.Integer) 2017-06-07 12:22:28.773 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/content],methods=[GET]}" onto public java.lang.String com.aibinxiao.HelloController.getContent() 2017-06-07 12:22:28.775 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/watch],methods=[GET]}" onto public java.lang.String com.aibinxiao.HelloController.watch(java.lang.Integer) 2017-06-07 12:22:28.776 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/{id}/talk],methods=[GET]}" onto public java.lang.String com.aibinxiao.HelloController.talk(java.lang.Integer) 2017-06-07 12:22:28.777 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/sing],methods=[GET]}" onto public java.lang.String com.aibinxiao.HelloController.sing(java.lang.Integer) 2017-06-07 12:22:28.778 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/cup],methods=[GET]}" onto public java.lang.String com.aibinxiao.HelloController.getCupSize() 2017-06-07 12:22:28.779 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/girl],methods=[GET]}" onto public java.lang.String com.aibinxiao.HelloController.getGirl() 2017-06-07 12:22:28.780 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/see/{id}],methods=[GET]}" onto public java.lang.String com.aibinxiao.HelloController.see(java.lang.Integer) 2017-06-07 12:22:28.786 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/say],methods=[POST]}" onto public java.lang.String com.aibinxiao.HelloController.say() 2017-06-07 12:22:28.789 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2017-06-07 12:22:28.791 INFO 21932 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2017-06-07 12:22:28.816 INFO 21932 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-06-07 12:22:28.817 INFO 21932 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-06-07 12:22:28.851 INFO 21932 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-06-07 12:22:29.056 INFO 21932 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-06-07 12:22:29.112 INFO 21932 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http) 2017-06-07 12:22:29.118 INFO 21932 --- [ main] com.aibinxiao.GirlApplication : Started GirlApplication in 4.599 seconds (JVM running for 10.335)
-
第三种方式,切换到项目目录的target目录,会出现一个.jar的文件,我们执行如下命令:
D:\InputProjects\learn_project\girl>cd target D:\InputProjects\learn_project\girl\target>java -jar girl-0.0.1-SNAPSHOT.jar
不知道为什么在Windows Dos命令无法成功,可能系统,但在Mac OS系统中却成功了,如图所示:
2.我们继续讲一下application配置文件的问题,我们之前对比了.properties和.yml文件的区别,并且我们推荐使用.yml文件格式进行配置,接下来,我们讲一下使用.yml文件在不同环境下使用的配置,比如说我们在开发环境和生产环境的一些配置项不一致我们要如何进行配置才能避免频繁改配置文件呢?
- 首先,我们需要配置一个主配置文件,可以把子配置文件公用的都放到主配置文件中
- 然后,配置各个环境的子配置文件,
- 最后,在主配置文件激活当前要使用的子配置文件即可
比如我们配置主配置文件:application.yml
spring:
profiles:
active: dev
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
开发环境配置文件:application-dev.yml
server:
port: 8081
context-path: /girl
cupSize: B
age: 18
content: "cupSzie: ${cupSize}, age: ${age}"
girl:
cupSize: B
age: 18
生产环境配置文件:application-prod.yml
server:
port: 8082
context-path: /girl
cupSize: F
age: 18
content: "cupSzie: ${cupSize}, age: ${age}"
girl:
cupSize: F
age: 18
这样,我们只需要在主配置文件中active参数这里配置当前需要激活的子配置文件即可!
3.我们接着看一下,如何在Java类中读取application.yml配置文件中的数据:
(1)比如我们要读取application-dev.yml文件中的cupSize,age,content值,要如何呢?
cupSize: B
age: 18
content: "cupSzie: ${cupSize}, age: ${age}"
我们只需要在要使用这些参数的Java类中,按照下面方式引入即可:
使用@Value注解,括号里填写通过${属性名}来获取配置文件中指定属性名的值
同时,我们通过上面的配置文件可以看到content属性,在当前配置中引入其他属性配置的值,同样是通过${属性名}来获取的。
@Value("${cupSize}")
private String cupSize;
@Value("${age}")
private Integer age;
@Value("${content}")
private String content;
(2)但是可以看到上面读取属性的值还有一个缺陷就是,现在一个女生的属性我们只定义了两个(cupSize,age),但是如果我们的属性很多的情况下,我们这样引入的话,就显得很繁杂了,我们要怎么办呢?我们可以只引入一个么?
A.答案是肯定的,我们可以在配置文件中定义一个girl,然后给她cupSize,age的属性值:
girl:
cupSize: B
age: 18
B.然后我们创建一个类GirlProperties,写上Girl的属性,并加入getter,setter,toString方法:
其中:@ConfigurationProperties(prefix = "girl")表示获取配置文件中,前缀为girl的配置;
@Component,表示把普通的POJO类实例化到Spring容器中,
相当于配置文件中的<bean id="" class="">
package com.aibinxiao;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created by aibin on 2017/6/4.
*/
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private String cupSize;
private Integer age;
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "GirlProperties{" +
"cupSize='" + cupSize + '\'' +
", age=" + age +
'}';
}
}
C.这样之后,我们就可以直接在需要使用这个Girl的类中,使用@Autowired注解直接注入这个类的实例化对象即可通过这个对象,调用这个对象的属性来获取配置文件中的值了:
@Autowired
private GirlProperties girlProperties;
4.我们讲一下SpringBoot中Controller的使用,首先看代码:
package com.aibinxiao;
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.*;
/**
* Created by aibin on 2017/6/4.
*/
@RestController
@RequestMapping("/hello")
public class HelloController {
// @RestController相当于@Controller+@ResponseBody
// 映射application配置文件中的值
// 配置文件默认是application.properties,但是因为.yml文件同前缀的可以省略并且也支持yml配置文件,所以推荐使用
@Value("${cupSize}")
private String cupSize;
@Value("${age}")
private Integer age;
@Value("${content}")
private String content;
@Autowired
private GirlProperties girlProperties;
// 使用post请求方式时,我们可以使用chorme中的Postman应用进行测试
@RequestMapping(value = "/say",method = RequestMethod.POST)
public String say(){
return "Hello Spring Boot!";
}
// 读取配置文件中的值
@RequestMapping(value = "/cup",method = RequestMethod.GET)
public String getCupSize(){
return cupSize;
}
@RequestMapping(value = "/content",method = RequestMethod.GET)
public String getContent(){
return content;
}
@RequestMapping(value = "/girl",method = RequestMethod.GET)
public String getGirl(){
return "Girl:["+"cupSize:"+girlProperties.getCupSize()+" age:"+girlProperties.getAge()+"]";
}
// 直接在url后面加参数id,使用@PathVariable
@RequestMapping(value = "/see/{id}",method = RequestMethod.GET)
public String see(@PathVariable("id") Integer id){
// url:http://localhost:8081/girl/hello/see/123
return "see me id: " + id;
}
// 在url前面加参数id,使用@PathVariable
// 注意@PathVariable中的id要和请求的url一致,但是形参是不需要一致吗比如myId
@RequestMapping(value = "/{id}/talk",method = RequestMethod.GET)
public String talk(@PathVariable("id") Integer myId){
// url:http://localhost:8081/girl/hello/123/talk
return "talk me id: " + myId;
}
// 使用普通加参数方法id,使用@RequestParam
// 注意@RequestParam中的id要和请求的url一致,但是形参是不需要一致吗比如myId
@RequestMapping(value = "/watch", method = RequestMethod.GET)
public String watch(@RequestParam("id") Integer myId){
// url:http://localhost:8081/girl/hello/watch?id=123
return "watch me id: " + myId;
}
// 我们可以设置是否必须传id, 并且设置默认值
/*@RequestMapping(value = "/sing", method = RequestMethod.GET)
public String sing(@RequestParam(value = "id", required = false,defaultValue = "0") Integer myId){
// url:http://localhost:8081/girl/hello/sing?id=123
return "sing id: " + myId;
}*/
// 比如为了简化代码,我们可以将上面的简化成如下
@GetMapping(value = "/sing")
public String sing(@RequestParam(value = "id", required = false,defaultValue = "0") Integer myId){
// url:http://localhost:8081/girl/hello/sing?id=123
return "sing id: " + myId;
}
}
- @Controller:处理http请求
- @RestController:Spring4之后新加的注解,原来返回json需要@Controller@ResponseBody进行配合使用,@ResponseBody要加在每个需要返回json的方法上,现在直接使用@RestController,即和就可以了,@RestController相当于@Controller加上@ResponseBody的效果。
- @RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
(1).value 和 method,也是最常用的
value:指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
value的uri值为以下三类:
A) 可以指定为普通的具体值;
B) 可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);
C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);
method:指定请求的method类型, GET、POST、PUT、DELETE等,不填默认都可以,不推荐;
(2).consumes 和 produces,
consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
(3).params和 headers,
params:指定request中必须包含某些参数值是,才让该方法处理。
headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
- @GetMapping,组合注解,即相当于RequestMapping使用的Get的请求方式
- @PathVariable,获取url中的数据,进行参数绑定。
- @RequestParam,获取请求参数的值,常用参数:value绑定参数,required设置是否必须传值,defaultValue默认值。
5.数据库操作
这里我们使用MySql数据库,数据持久层使用Spring-Data-Jpa组件,JPA(Java Persistence API)是定义了一系列对象持久化的标准,目前实现这一规范的产品有Hibernate、TopLink等。其实Spring-Data-Jpa是对Hibernate的一个整合。
(1)首先,我们需要在pom.xml文件中添加Spring-Data-Jpa和连接mysql需要的依赖:
<!-- 使用SpringBoot data-jpa要用到的依赖,持久层 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 连接mysql需要用到的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
(2)然后,我们在主配置文件中加入连接数据库的配置,以及jpa的相关配置:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: root
jpa:
hibernate:
ddl-auto: create
show-sql: true
datasource:
driver-class-name: com.mysql.jdbc.Driver 驱动类
url: jdbc:mysql://127.0.0.1:3306/dbgirl 数据库连接url
username: root mysql的用户名
password: root mysql的用户密码
jpa:
hibernate:
ddl-auto: update 这里有create,create-drop,none,update,validate五个选择
create:程序每次执行都自动帮我们创建一个空表,如果已经存在会先删除;
create-drop:应用停下来的时候,就会把表删除
none:默认无任何操作;
update:第一次运行自动创建表结构,如果之前里面有数据不会删除,会保留;
validate:会验证类里面的属性跟表结构是否一致,不一致就会报错。
show-sql: true 是否显示sql执行语句
(3)然后,我们需要在mysql中创建一个名字为dbgirl的数据库,否则会说不存在dbgirl的数据库;
(4)我们再创建一个Girl的实体类,注意添加无参构造函数:
@Entity,表示这个类对应数据库中的一个表
@Id,表示主键Id,一般都是自增
@GeneratedValue,表示主键自增
package com.aibinxiao;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by aibin on 2017/6/5.
*/
@Entity
public class Girl {
@Id
@GeneratedValue
private Integer id;
private String cupSize;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Girl() {
}
}
(5)这个时候,启动项目,会发现数据库中会生成一张名称表girl的表,因为刚才数数据库配置实用的是create。并且在console中可以看到创建表的sql语句;
(6)我们开始写增删改查的接口
GirlRepository接口:继承自JpaRepository,数据持久层的相关操作,继承之后含有基本的增删改查数据库操作方法
package com.aibinxiao;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Created by aibin on 2017/6/5.
*/
public interface GirlRepository extends JpaRepository<Girl, Integer> {
// 通过年龄进行查询
public List<Girl> findByAge(Integer age);
}
GirlService类:进行业务逻辑处理
package com.aibinxiao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by aibin on 2017/6/5.
*/
@Service
public class GirlService {
@Autowired
private GirlRepository girlRepository;
// 事务操作,同时操作多条数据,一个操作失败,其他操作都失败
@Transactional
public void insertTwo(){
Girl girlA = new Girl();
girlA.setAge(18);
girlA.setCupSize("F");
girlRepository.save(girlA);
Girl girlB = new Girl();
girlB.setAge(19);
girlB.setCupSize("AAAA");// 数据库该字段长度为1,报错,没有加事务前,girlA会被添加到数据库,而girlB不会;添加事务后,girB添加时出错,同时girlA也不会添加
girlRepository.save(girlB);
}
}
GirlController类:自动注入GirlRepository和GirlService
package com.aibinxiao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Created by aibin on 2017/6/5.
*/
@RestController
public class GirlController {
@Autowired
private GirlRepository girlRepository;
@Autowired
private GirlService girlService;
/**
* 获取所有女生的信息
* @return
*/
@GetMapping(value = "/girls")
public List<Girl> girlList(){
List<Girl> girls = girlRepository.findAll();
return girls;
}
/**
* 新增一个女生
* @param cupSize
* @param age
* @return
*/
@PostMapping(value = "/addgirl")
public String addGirl(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age){
Girl girl = new Girl();
girl.setAge(age);
girl.setCupSize(cupSize);
Girl newGirl = girlRepository.save(girl);
return newGirl.toString();
}
/**
* 根据id查询一个女生
* @param id
* @return
*/
@GetMapping(value = "/getone/{id}")
public Girl findOne(@PathVariable(value = "id") Integer id){
return girlRepository.findOne(id);
}
/**
* 根据id更新一个女生的信息
* @param id
* @param cupSize
* @param age
* @return
*/
@PutMapping(value = "/update/{id}")
public Girl updateGirl(@PathVariable(value = "id") Integer id,
@RequestParam(value = "cupSize") String cupSize,
@RequestParam(value = "age") Integer age){
Girl girl = new Girl();
girl.setId(id);
girl.setCupSize(cupSize);
girl.setAge(age);
girlRepository.save(girl);
return girlRepository.getOne(id);
}
/**
* 根据id删除一个女生
* @param id
*/
@DeleteMapping(value = "/delete/{id}")
public void deleteGirl(@PathVariable(value = "id") Integer id){
girlRepository.delete(id);
}
/**
* 根据年龄查询
* @param age
* @return
*/
@GetMapping(value = "/findbyage/{age}")
public List<Girl> findByAge(@PathVariable(value = "age") Integer age){
return girlRepository.findByAge(age);
}
@PostMapping(value = "insettwo")
public void insertTwoGirl(){
girlService.insertTwo();
}
}
通过访问Controller中的接口,我们就可以完成最基本的数据库操作了!大家可以尝试一下!
本文为原创文章,如果对你有一点点的帮助,别忘了点赞哦!比心!如需转载,请注明出处,谢谢!