前言
本系列文章为陈韶健老师的《SpringCloud与Docker高并发微服务架构实施》的代码实现,仅供个人学习交流所用,如有侵权必删。
一、开发搭建
使用IDEA,搭建SpringBoot项目
选择下图
pom,xml:如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-demo</name>
<description>spring-boot-demo</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.example.springbootdemo.SpringBootDemoApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
使用JPA
JPA教程提供了Java持久性API的基本和高级概念。此JPA教程专为初学者和专业人士设计。
JPA只是一个简化对象关系映射来管理Java应用程序中的关系数 据的规范。 它提供了一个平台,可以直接使用对象而不是使用SQL语句。//更多请阅读:https://www.yiibai.com/jpa/
数据库配置
在Mysql中新建一个test数据库,配置如下
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=123456
JPA配置
下面是JPA配置,配置中我们将“ddl-auto”设置为“update”,表示将根据实体设计在程序运行时自动更新表结构。
#是否在控制台打印JPA执行过程生成的SQL
spring.jpa.show-sql=true
#表示JPA对应的数据库是MySQL
spring.jpa.database=mysql
#表示在项目启动时根据实体类更新数据库中的表
spring.jpa.hibernate.ddl-auto=update
#表示使用的数据库方言是MySQL57Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
jpa的使用需要对jpa进行配置,用来扫描实体类和dao接口。新建一个配置类
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "com.**.dao")
@EntityScan(basePackages = "com.**.entity")
public class JpaConfiguration {
@Bean
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
return new PersistenceExceptionTranslationPostProcessor();
}
}
@EntityScan是扫描实体类的路径,@EnableJpaRepositories是扫描dao层的路径
数据实体类设计
@Entity
@Table(name = "country")
@Data
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String countryName;
private String countryCode;
}
@Table是指定生成的表名
dao接口设计
@Repository
public interface CountryDao extends JpaRepository<Country, Long> {
}
单元测试
@SpringBootTest
@ContextConfiguration(classes = {JpaConfiguration.class,SpringBootDemoApplication.class})
class SpringBootDemoApplicationTests {
@Autowired
private CountryDao countryDao;
public void createCountry(){
Country country=new Country();
country.setCountryCode("86");
country.setCountryName("中国");
countryDao.save(country);
assert country.getId()>0:"create error";
}
@Test
void contextLoads() {
createCountry();
List<Country> countryList=countryDao.findAll();
for (Country country:countryList){
System.out.println("=====country name="+country.getCountryName());
}
}
}
如果运行成功并在控制台打印出“=====country name=中国”说明测试成功。
前台使用Thymeleaf
在创建springBoot项目时只要勾选Thymeleaf就会有如下配置
# THYMELEAF (ThymeleafAutoConfiguration)
# 开启模板缓存(默认值: true )
spring.thymeleaf.cache=true
# 检查模板是否存在,然后再呈现
spring.thymeleaf.check-template=true
# 检查模板位置是否正确(默认值 :true )
spring.thymeleaf.check-template-location=true
#Content-Type 的值(默认值: text/html )
spring.thymeleaf.content-type=text/html
# 开启 MVC Thymeleaf 视图解析(默认值: true )
spring.thymeleaf.enabled=true
# 模板编码
spring.thymeleaf.encoding=UTF-8
# 要被排除在解析之外的视图名称列表,⽤逗号分隔
spring.thymeleaf.excluded-view-names=
# 要运⽤于模板之上的模板模式。另⻅ StandardTemplate-ModeHandlers( 默认值: HTML5)
spring.thymeleaf.mode=HTML5
# 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ )
spring.thymeleaf.prefix=classpath:/templates/
# 在构建 URL 时添加到视图名称后的后缀(默认值: .html )
spring.thymeleaf.suffix=.html
Controller实现
@Controller
public class CountryController {
@Autowired
private CountryDao countryDao;
@RequestMapping(value = "/")
public String test(ModelMap modelMap){
List<Country> list= countryDao.findAll();
modelMap.addAttribute("countrys",list);
return "index";
}
}
页面实现
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<title>国家代码</title>
</head>
<body>
<!--/*@thymesVar id="countrys" type="com"*/-->
<ul th:each="country:${countrys}">
<li>
<p th:text="'代码:'+${country.countryCode}"></p>
<p th:text="'国家:'+${country.countryName}"></p>
</li>
</ul>
</body>
</html>
运行
成功启动项目后在访问http://localhost:8080/在页面中显示成功