编写目标:使用springboot+jpa调用Thymeleaf模板显示数据库表的数据
1:依赖注入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<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>
<version>2.1.6.RELEASE</version>
</dependency>
2:编写业务模型类(较为简单,不展示)
3:编写jpa类
@Component
public interface StockRepo extends PagingAndSortingRepository<Stock, Integer> {
}
4:编写业务逻辑类
@Service
public class StockService {
@Autowired
private StockRepo stockRepo;
public List<Stock> getAllStock(){
return (List<Stock>)stockRepo.findAll();
}
}
5:编写控制器类
@RestController
public class Controller {
@Autowired
StockService stockService;
@RequestMapping("/showList")
public ModelAndView showList(){
ModelAndView modelAndView = new ModelAndView("list");
modelAndView.addObject("stocks",stockService.getAllStock());
return modelAndView;
}
6:编写配置文件
spring:
jpa:
show-sql: true
hibernate:
dll-auto: validate
datasource:
url: jdbc:mysql://localhost:3306/stock?serverTimezone=GMT
username: root
password: hsp
driver-class-name: com.mysql.cj.jdbc.Driver
thymeleaf:
enabled: true
content-type: text/html
check-template-location: true
cache: false
prefix: classpath:/templates/
suffix: .html
7:编写html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>库存列表</title>
</head>
<body>
<table border="2">
<tr>
<td>库存编号</td>
<td>库存货物</td>
<td>数量</td>
<td>描述</td>
</tr>
<tr th:each="stock : ${stocks}">
<td th:text="${stock.ID}"></td>
<td th:text="${stock.name}"></td>
<td th:text="${stock.num}"></td>
<td th:text="${stock.description}"></td>
</tr>
</table>
</body>
</html>
项目错误总结:
第一次错误是连接Mysql数据库发生通信链路问题,无法启动项目,花费许多时间排查,在Mysql文件目录查看错误日志,发现原因是报错多个Bad handshake,又是不断调试,最终解决方法是看到一位前辈的方法分享,因为5.7.30默认打开了SSL连接,在连接串使用useSSL=false,或者在my.ini文件中增加
[mysqld]
skip_ssl
之后进行了添加连接串使用,无法运行,在my.ini文件中添加skip_ssl之后成功运行!!
第二次错误是连接游览器连接无法显示,对比查找代码发现是业务模型类的代码没写构造器,一个小的失误。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。