2.1.1
创建
Maven
工程
使用
idea
工具创建一个
maven
工程,该工程为普通的
java
工程即可
2.1.2
添加
SpringBoot
的起步依赖
SpringBoot
要求,项目要继承
SpringBoot
的起步依赖
spring-boot-starter-parent
SpringBoot
要集成
SpringMVC
进行
Controller
的开发,所以项目要导入
web
的启动依赖
1
2
3
4
5
6 1<parent>
2<groupId>org.springframework.boot</groupId>
3<artifactId>spring-boot-starter-parent</artifactId>
4<version>2.0.1.RELEASE</version>
5</parent>
6
1
2
3
4
5
6
7 1<dependencies>
2<dependency>
3<groupId>org.springframework.boot</groupId>
4<artifactId>spring-boot-starter-web</artifactId>
5</dependency>
6</dependencies>
7
2.1.3
编写
SpringBoot
引导类
要通过
SpringBoot
提供的引导类起步
SpringBoot
才可以进行访问
1
2
3
4
5
6
7
8
9
10 1package com.dharmayard;
2import org.springframework.boot.SpringApplication;
3import org.springframework.boot.autoconfigure.SpringBootApplication;
4@SpringBootApplication
5public class MySpringBootApplication {
6public static void main(String[] args) {
7SpringApplication.run(MySpringBootApplication.class);
8}
9}
10
2.1.4
编写
Controller
在引导类
MySpringBootApplication
同级包或者子级包中创建
QuickStartController
1
2
3
4
5
6
7
8
9
10
11
12
13 1package com.dharmayard.controller;
2import org.springframework.stereotype.Controller;
3import org.springframework.web.bind.annotation.RequestMapping;
4import org.springframework.web.bind.annotation.ResponseBody;
5@Controller
6public class QuickStartController {
7@RequestMapping("/quick")
8@ResponseBody
9public String quick(){
10return "springboot 访问成功!";
11}
12}
13
2.1.5
测试
执行SpringBoot
起步类的主方法,控制台打印日志:
通过日志发现,
Tomcat started on port(s): 8080 (http) with context path ''
tomcat
已经起步,端口监听
8080
,
web
应用的虚拟工程名称为空
打开浏览器访问
url
地址为:
http://localhost:8080/quick
2.2.3 SpringBoot工程热部署
我们在开发中反复修改类、页面等资源,每次修改后都是需要重新启动才生效,这样每次启动都很麻烦,浪费了大
量的时间,我们可以在修改代码后不重启就能生效,在 pom.xml 中添加如下配置就可以实现这样的功能,我们称
之为热部署。
1
2
3
4
5
6 1<!--热部署配置-->
2<dependency>
3<groupId>org.springframework.boot</groupId>
4<artifactId>spring-boot-devtools</artifactId>
5</dependency>
6
因为Intellij IEDA默认情况下不会自动编译,需要对IDEA进行自动编译的设置,如下:
然后 Shift+Ctrl+Alt+/,选择Registry
四、SpringBoot的配置文件
4.1 SpringBoot配置文件类型
4.1.1 SpringBoot配置文件类型和作用
SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用
application.properties或者application.yml(application.yaml)进行配置。
SpringBoot默认会从Resources目录下加载application.properties或application.yml(application.yaml)文件
其中,application.properties文件是键值对类型的文件,之前一直在使用,所以此处不在对properties文件的格式
进行阐述。除了properties文件外,SpringBoot还可以使用yml文件进行配置,下面对yml文件进行讲解。
4.1.2 application.yml配置文件
4.1.2.1 yml配置文件简介
YML文件格式是YAML (YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数
据数据序列化格式,并且容易被人类阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导
入,比如: C/C++, Ruby, Python, Java, Perl, C#, PHP等。YML文件是以
数据为核心的,比传统的xml方式更加简
洁。
YML文件的扩展名可以使用.yml或者.yaml。
4.1.2.2 yml配置文件的语法
4.1.2.2.1 配置普通数据
语法: key: value
示例代码:
1
2 1name: haohao
2
注意:value之前有一个空格
4.1.2.2.2 配置对象数据
语法:
key:
key1: value1
key2: value2
或者:
key: {key1: value1,key2: value2}
示例代码:
1
2
3
4
5
6
7 1person:
2name: haohao
3age: 31
4addr: beijing
5#或者
6person: {name: haohao,age: 31,addr: beijing}
7
注意:key1前面的空格个数不限定,在yml语法中,相同缩进代表同一个级别
4.1.2.2.2 配置Map数据
同上面的对象写法
4.1.2.2.3 配置数组(List、Set)数据
语法:
key:
- value1
- value2
或者:
key: [value1,value2]
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 1city:
2- beijing
3- tianjin
4- shanghai
5- chongqing
6#或者
7city: [beijing,tianjin,shanghai,chongqing]
8#集合中的元素是对象形式
9student:
10- name: zhangsan
11age: 18
12score: 100
13- name: lisi
14age: 28
15score: 88
16- name: wangwu
17age: 38
18score: 90
19
注意:value1与之间的 – 之间存在一个空格
4.1.3 SpringBoot配置信息的查询
上面提及过,SpringBoot的配置文件,主要的目的就是对配置信息进行修改的,但在配置时的key从哪里去查询
呢?我们可以查阅SpringBoot的官方文档
文档URL:https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/reference/htmlsingle/\#common-applicationproperties
常用的配置摘抄如下:
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 1# QUARTZ SCHEDULER (QuartzProperties)
2spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode.
3spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.
4sql # Path to the SQL file to use to initialize the database schema.
5spring.quartz.job-store-type=memory # Quartz job store type.
6spring.quartz.properties.*= # Additional Quartz Scheduler properties.
7# ----------------------------------------
8# WEB PROPERTIES
9# ----------------------------------------
10# EMBEDDED SERVER CONFIGURATION (ServerProperties)
11server.port=8080 # Server HTTP port.
12server.servlet.context-path= # Context path of the application.
13server.servlet.path=/ # Path of the main dispatcher servlet.
14# HTTP encoding (HttpEncodingProperties)
15spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to
16the "Content-Type" header if not set explicitly.
17# JACKSON (JacksonProperties)
18spring.jackson.date-format= # Date format string or a fully-qualified date format
19class name. For instance, `yyyy-MM-dd HH:mm:ss`.
20# SPRING MVC (WebMvcProperties)
21spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher
22servlet.
23spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
24spring.mvc.view.prefix= # Spring MVC view prefix.
25spring.mvc.view.suffix= # Spring MVC view suffix.
26# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
27spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Autodetected based on the URL by default.
28spring.datasource.password= # Login password of the database.
29spring.datasource.url= # JDBC URL of the database.
30spring.datasource.username= # Login username of the database.
31# JEST (Elasticsearch HTTP client) (JestProperties)
32spring.elasticsearch.jest.password= # Login password.
33spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use.
34spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use.
35spring.elasticsearch.jest.read-timeout=3s # Read timeout.
36spring.elasticsearch.jest.username= # Login username.
37
4.2 配置文件与配置类的属性映射方式
4.2.1 使用注解@Value映射
我们可以通过@Value注解将配置文件中的值映射到一个Spring管理的Bean的字段上
例如:
application.properties配置如下:
1
2
3
4 1person:
2name: zhangsan
3age: 18
4
或者,application.yml配置如下:
1
2
3
4 1person:
2name: zhangsan
3age: 18
4
实体Bean代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13 1@Controller
2public class QuickStartController {
3@Value("${person.name}")
4private String name;
5@Value("${person.age}")
6private Integer age;
7@RequestMapping("/quick")
8@ResponseBody
9public String quick(){
10return "springboot 访问成功! name="+name+",age="+age;
11}
12}
13
浏览器访问地址:http://localhost:8080/quick 结果。
4.2.2 使用注解@ConfigurationProperties映射
通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映
射
实体Bean代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 1@Controller
2@ConfigurationProperties(prefix = "person")
3public class QuickStartController {
4private String name;
5private Integer age;
6@RequestMapping("/quick")
7@ResponseBody
8public String quick(){
9return "springboot 访问成功! name="+name+",age="+age;
10} p
11ublic void setName(String name) {
12this.name = name;
13} p
14ublic void setAge(Integer age) {
15this.age = age;
16}
17}
18
注意:使用@ConfigurationProperties方式可以进行配置文件与实体字段的自动映射,但需要字段必须提供set方
法才可以,而使用@Value注解修饰的字段不需要提供set方法
五、SpringBoot与整合其他技术
5.1 SpringBoot整合Mybatis
5.1.1 添加Mybatis的起步依赖
5.1.2 添加数据库驱动坐标
1
2
3
4
5
6
7
8
9
10
11
12
13
14 1<!--mybatis起步依赖-->
2<dependency>
3 <groupId>org.mybatis.spring.boot</groupId>
4 <artifactId>mybatis-spring-boot-starter</artifactId>
5 <version>2.0.0</version>
6</dependency>
7
8<!-- MySQL连接驱动 -->
9<dependency>
10 <groupId>mysql</groupId>
11 <artifactId>mysql-connector-java</artifactId>
12 <scope>runtime</scope>
13</dependency>
14
5.1.3 添加数据库连接信息
在application.properties中添加数据量的连接信息
1
2
3
4
5
6
7 1#DB Configuration:
2spring.datasource.driverClassName=com.mysql.jdbc.Driver
3spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?
4useUnicode=true&characterEncoding=utf8
5spring.datasource.username=root
6spring.datasource.password=root
7
5.1.4 创建user表
在test数据库中创建user表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 1-- ----------------------------
2-- Table structure for `user`
3-- ----------------------------
4DROP TABLE IF EXISTS `user`;
5CREATE TABLE `user` (
6`id` int(11) NOT NULL AUTO_INCREMENT,
7`username` varchar(50) DEFAULT NULL,
8`password` varchar(50) DEFAULT NULL,
9`name` varchar(50) DEFAULT NULL,
10PRIMARY KEY (`id`)
11) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
12-- ----------------------------
13-- Records of user
14-- ----------------------------
15INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '张三');
16INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');
17
5.1.5 创建实体Bean
1
2
3
4
5
6
7
8
9
10
11
12 1public class User {
2// 主键
3private Long id;
4// 用户名
5private String username;
6// 密码
7private String password;
8// 姓名
9private String name;
10//此处省略getter和setter方法 .. ..
11}
12
但是建议使用mybatis自动生成工具:自写插件。
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
49
50
51
52
53
54
55
56
57
58
59
60 1package cn.dharmayard.mybatis.comment.generator;
2
3import java.sql.Timestamp;
4import org.mybatis.generator.api.IntrospectedColumn;
5import org.mybatis.generator.api.IntrospectedTable;
6import org.mybatis.generator.api.dom.java.Field;
7import org.mybatis.generator.api.dom.java.TopLevelClass;
8import org.mybatis.generator.internal.DefaultCommentGenerator;
9import org.mybatis.generator.internal.util.StringUtility;
10
11public class DharmayardCommentGenerator
12 extends DefaultCommentGenerator
13{
14 public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn)
15 {
16 if ((introspectedColumn.getRemarks() != null) && (!introspectedColumn.getRemarks().equals("")))
17 {
18 StringBuffer sb = new StringBuffer();
19 field.addJavaDocLine("/**");
20 field.addJavaDocLine(" * <pre>");
21 if (introspectedColumn.getRemarks() != null) {
22 field.addJavaDocLine(" * 表字段注释 : " + introspectedColumn.getRemarks());
23 }
24 sb.append(" * 表字段 : ");
25 sb.append(introspectedTable.getFullyQualifiedTable());
26 sb.append('.');
27 sb.append(introspectedColumn.getActualColumnName());
28 field.addJavaDocLine(sb.toString());
29 field.addJavaDocLine(" * </pre>");
30 field.addJavaDocLine(" */");
31 }
32 }
33
34 public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable)
35 {
36 StringBuilder sb = new StringBuilder();
37 topLevelClass.addJavaDocLine("/**");
38 String remarks = introspectedTable.getRemarks();
39 if (StringUtility.stringHasValue(remarks))
40 {
41 topLevelClass.addJavaDocLine(" * Database Table Remarks:");
42 String[] remarkLines = remarks.split(System.getProperty("line.separator"));
43 String[] var6 = remarkLines;
44 int var7 = remarkLines.length;
45 for (int var8 = 0; var8 < var7; var8++)
46 {
47 String remarkLine = var6[var8];
48 topLevelClass.addJavaDocLine(" * " + remarkLine);
49 }
50 }
51 topLevelClass.addJavaDocLine(" *");
52 sb.append(" * the database table ");
53 sb.append(introspectedTable.getFullyQualifiedTable());
54 topLevelClass.addJavaDocLine(sb.toString());
55 topLevelClass.addJavaDocLine(" * create by " + new Timestamp(System.currentTimeMillis()));
56 topLevelClass.addJavaDocLine(" */");
57 }
58}
59
60
然后在pom中使用指定生成插件
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 1<build>
2 <plugins>
3 <plugin>
4 <groupId>org.apache.maven.plugins</groupId>
5 <artifactId>maven-compiler-plugin</artifactId>
6 <version>3.6.0</version>
7 <configuration>
8 <source>1.8</source>
9 <target>1.8</target>
10 </configuration>
11 </plugin>
12 <plugin>
13 <groupId>org.springframework.boot</groupId>
14 <artifactId>spring-boot-maven-plugin</artifactId>
15 </plugin>
16 <!-- mybatis自动生成代码 -->
17 <plugin>
18 <groupId>org.mybatis.generator</groupId>
19 <artifactId>mybatis-generator-maven-plugin</artifactId>
20 <version>1.3.2</version>
21 <!-- 无法让插件编译本地代码,只能这样搞 -->
22 <dependencies>
23 <!--
24 <dependency>
25 <groupId>com.xuwhyse</groupId>
26 <artifactId>mybatis-generate-self</artifactId>
27 <version>1.0.0</version>
28 <scope>system</scope>
29 <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/mybatis-generate-self-1.0.0.jar</systemPath>
30 </dependency>
31 -->
32 <!-- -->
33 <dependency>
34 <groupId>cn.dharmayard.mybatis</groupId>
35 <artifactId>mybatis-comment-plugin</artifactId>
36 <version>1.0.0</version>
37 </dependency>
38 </dependencies>
39 <configuration>
40 <verbose>true</verbose>
41 <overwrite>true</overwrite>
42 </configuration>
43 </plugin>
44 </plugins>
45</build>
46
然后在项目resource目录下放入generatorConfig.xml文件。并修改其中的db连接,设置mysql的连接jar包路径,生成java model以及mapper.xml和mapper.java文件存放的路径位置,和要根据哪张表生成实体的表明和对应实体名。
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 1<?xml version="1.0" encoding="UTF-8" ?>
2<!DOCTYPE generatorConfiguration
3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
5
6<generatorConfiguration>
7
8 <!-- 自动生成代码,只加了mybatis2个包和plugin,再加上这个文件的配置就行,不依赖其他信息 mybatis-generator:generate -->
9 <!-- !!!! Driver Class Path !!!! -->
10 <classPathEntry
11 location="D:\develop\apache-maven-3.5.3\repo\mysql\mysql-connector-java\5.1.41\mysql-connector-java-5.1.41.jar"/>
12
13 <context id="context" defaultModelType="flat" targetRuntime="MyBatis3">
14
15 <property name="javaFileEncoding" value="UTF-8"/>
16
17 <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"/>
18 <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
19 <!--支持分页-->
20 <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>
21
22 <commentGenerator
23 type="cn.dharmayard.mybatis.comment.generator.DharmayardCommentGenerator">
24 <property name="javaFileEncoding" value="UTF-8"/>
25 <property name="suppressAllComments" value="true"/>
26 <property name="suppressDate" value="true"/>
27 </commentGenerator>
28
29 <!-- !!!! Database Configurations !!!! -->
30 <jdbcConnection driverClass="com.mysql.jdbc.Driver"
31
32 connectionURL="jdbc:mysql://192.168.0.101:3306/lottery_builder" userId="root"
33 password="123456"/>
34 <javaTypeResolver>
35 <property name="forceBigDecimals" value="false"/>
36 </javaTypeResolver>
37
38 <!-- !!!! Model Configurations !!!! -->
39 <javaModelGenerator targetPackage="com.dharmayard.lottery.model"
40 targetProject="src/main/java">
41 <property name="enableSubPackages" value="false"/>
42 <property name="trimStrings" value="true"/>
43 </javaModelGenerator>
44
45 <!-- !!!! Mapper XML Configurations !!!! -->
46 <sqlMapGenerator targetPackage="mapper"
47 targetProject="src/main/resources">
48 <property name="enableSubPackages" value="false"/>
49 </sqlMapGenerator>
50
51 <!-- !!!! Mapper Interface Configurations !!!! -->
52 <javaClientGenerator targetPackage="com.dharmayard.lottery.mapper"
53 targetProject="src/main/java" type="XMLMAPPER">
54 <property name="enableSubPackages" value="false"/>
55 </javaClientGenerator>
56
57
58 <table tableName="lottery_dlt_reward" domainObjectName="DltReward" enableCountByExample="false"
59 enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false">
60
61 </table>
62
63
64
65 </context>
66</generatorConfiguration>
67
以上配置完成后可以点击maven插件生成了。
注意开发规范:如果生成的mapper接口名为DltBallOrderMapper里面是插件生成的原生方法,那我们新开发的接口一般是写在一个新建的名为DltBallOrderExtendsMapper的接口里面,如下
1
2
3
4
5
6 1public interface DltBallOrderExtendsMapper extends DltBallOrderMapper {
2 DltBallOrder selectByPeriodNo(String periodNo);
3
4 DltBallOrder selectDltBallOrderByParams(Map<String, Object> params);
5}
6
5.1.6 编写Mapper
1
2
3
4
5 1@Mapper
2public interface UserMapper {
3public List<User> queryUserList();
4}
5
注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中
5.1.7 配置Mapper映射文件
在src\main\resources\mapper路径下加入UserMapper.xml配置文件"
1
2
3
4
5
6
7
8
9 1<?xml version="1.0" encoding="utf-8" ?>
2<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
3"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
4<mapper namespace="com.itheima.mapper.UserMapper">
5<select id="queryUserList" resultType="user">
6select * from user
7</select>
8</mapper>
9
5.1.8 在application.properties中添加mybatis的信息
1
2
3
4
5
6 1#spring集成Mybatis环境
2#pojo别名扫描包
3mybatis.type-aliases-package=com.itheima.domain
4#加载Mybatis映射文件
5mybatis.mapper-locations=classpath:mapper/*Mapper.xml
6
5.1.9 编写测试Controller
1
2
3
4
5
6
7
8
9
10
11
12 1@Controller
2public class MapperController {
3@Autowired
4private UserMapper userMapper;
5@RequestMapping("/queryUser")
6@ResponseBody
7public List<User> queryUser(){
8List<User> users = userMapper.queryUserList();
9return users;
10}
11}
12
5.1.10 测试
localhost:8080/queryUser
5.2 SpringBoot整合Junit
5.2.1 添加Junit的起步依赖
1
2
3
4
5
6
7 1<!--测试的起步依赖-->
2<dependency>
3<groupId>org.springframework.boot</groupId>
4<artifactId>spring-boot-starter-test</artifactId>
5<scope>test</scope>
6</dependency>
7
5.2.2 编写测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 1package com.dharmayard.test;
2import com.dharmayard.MySpringBootApplication;
3import com.dharmayard.domain.User;
4import com.dharmayard.mapper.UserMapper;
5import org.junit.Test;
6import org.junit.runner.RunWith;
7import org.springframework.beans.factory.annotation.Autowired;
8import org.springframework.boot.test.context.SpringBootTest;
9import org.springframework.test.context.junit4.SpringRunner;
10import java.util.List;
11
12@RunWith(SpringRunner.class)
13@SpringBootTest(classes = MySpringBootApplication.class)
14public class MapperTest {
15@Autowired
16private UserMapper userMapper;
17@Test
18public void test() {
19List<User> users = userMapper.queryUserList();
20System.out.println(users);
21}
22}
23
其中,
SpringRunner继承自SpringJUnit4ClassRunner,使用哪一个Spring提供的测试测试引擎都可以
1
2 1public final class SpringRunner extends SpringJUnit4ClassRunner
2
@SpringBootTest的属性指定的是引导类的字节码对象
5.3 SpringBoot整合Spring Data JPA
5.3.1
添加
Spring Data JPA
的起步依赖
1
2
3
4
5
6 1<!-- springBoot JPA的起步依赖 -->
2<dependency>
3<groupId>org.springframework.boot</groupId>
4<artifactId>spring-boot-starter-data-jpa</artifactId>
5</dependency>
6
5.3.2
添加数据库驱动依赖
1
2
3
4
5
6 1<!-- MySQL连接驱动 -->
2<dependency>
3<groupId>mysql</groupId>
4<artifactId>mysql-connector-java</artifactId>
5</dependency>
6
5.3.3
在
application.properties
中配置数据库和
jpa
的相关属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14 1
2#DB Configuration:
3spring.datasource.driverClassName=com.mysql.jdbc.Driver
4spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?
5useUnicode=true&characterEncoding=utf8
6spring.datasource.username=root
7spring.datasource.password=root
8#JPA Configuration:
9spring.jpa.database=MySQL
10spring.jpa.show-sql=true
11spring.jpa.generate-ddl=true
12spring.jpa.hibernate.ddl-auto=update
13spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
14
5.3.4
创建实体配置实体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 1@Entity
2public class User {
3// 主键
4@Id
5@GeneratedValue(strategy = GenerationType.IDENTITY)
6private Long id;
7// 用户名
8private String username;
9// 密码
10private String password;
11// 姓名
12private String name;
13//此处省略setter和getter方法... ...
14}
15
5.3.5
编写
UserRepository
1
2
3
4
5 1
2public interface UserRepository extends JpaRepository<User,Long>{
3public List<User> findAll();
4}
5
5.3.6
编写测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14 1
2@RunWith(SpringRunner.class)
3@SpringBootTest(classes=MySpringBootApplication.class)
4public class JpaTest {
5@Autowired
6private UserRepository userRepository;
7@Test
8public void test(){
9List<User> users = userRepository.findAll();
10System.out.println(users);
11}
12}
13
14
5.3.7
控制台打印信息
注意:如果是
jdk9
,执行报错因为
jdk
缺少相应的
jar
解决方案:手动导入对应的
maven
坐标,如下:
1
2
3
4
5
6
7 1<!--jdk9需要导入如下坐标-->
2<dependency>
3<groupId>javax.xml.bind</groupId>
4<artifactId>jaxb-api</artifactId>
5<version>2.3.0</version>
6</dependency>
7
5.4 SpringBoot
整合
Redis
5.4.1
添加
redis
的起步依赖
1
2
3
4
5
6 1<!-- 配置使用redis启动器 -->
2<dependency>
3<groupId>org.springframework.boot</groupId>
4<artifactId>spring-boot-starter-data-redis</artifactId>
5</dependency>
6
5.4.2
配置
redis
的连接信息
1
2
3
4 1#Redis
2spring.redis.host=127.0.0.1
3spring.redis.port=6379
4
5.4.3
注入
RedisTemplate
测试
redis
操作
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 1
2@RunWith(SpringRunner.class)
3@SpringBootTest(classes = SpringbootJpaApplication.class)
4public class RedisTest {
5@Autowired
6private UserRepository userRepository;
7@Autowired
8private RedisTemplate<String, String> redisTemplate;
9@Test
10public void test() throws JsonProcessingException {
11//从redis缓存中获得指定的数据
12
13String userListData = redisTemplate.boundValueOps("user.findAll").get();
14//如果redis中没有数据的话
15if(null==userListData){
16//查询数据库获得数据
17List<User> all = userRepository.findAll();
18//转换成json格式字符串
19ObjectMapper om = new ObjectMapper();
20userListData = om.writeValueAsString(all);
21//将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库
22redisTemplate.boundValueOps("user.findAll").set(userListData);
23System.out.println("===============从数据库获得数据===============");
24}else{
25System.out.println("===============从redis缓存中获得数据===============");
26} S
27ystem.out.println(userListData);
28}
29}
30