編寫目標:使用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之後成功運行!!
第二次錯誤是連接遊覽器連接無法顯示,對比查找代碼發現是業務模型類的代碼沒寫構造器,一個小的失誤。