Spring Boot繼承了Spring框架的緩存管理功能宦赠,通過使用@EnableCaching注解開啟基于注解的緩存支持,Spring Boot就可以啟動緩存管理的自動化配置贺奠。
接下來針對Spring Boot支持的默認緩存管理進行講解
#### **5.1.1** 基礎環(huán)境搭建
**1.準備數據**
使用創(chuàng)建的springbootdata的數據庫芭概,該數據庫有兩個表t_article和t_comment
**2.創(chuàng)建項目,功能編寫**
(1)在Dependencies依賴選擇項中添加SQL模塊中的JPA依賴敢朱、MySQL依賴和Web模塊中的Web依賴?
(2)編寫數據庫表對應的實體類,并使用JPA相關注解配置映射關系?
```java
? ? ? import javax.persistence.*;
? ? ? @Entity(name = "t_comment")? // 設置ORM實體類栖茉,并指定映射的表名
? ? ? public class Comment {
@Id?? // 表明映射對應的主鍵id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 設置主鍵自增策略
private Integer id;
private String content;
private String author;
@Column(name = "a_id")
//指定映射的表字段名
private Integer aId;
// 省略屬性getXX()和setXX()方法
// 省略toString()方法
? ? ? }
```
(3)編寫數據庫操作的Repository接口文件
```java
public interface CommentRepository extends
JpaRepository<Comment,Integer> {
//根據評論id修改評論作者author
@Transactional
@Modifying
@Query("update t_comment c set c.author = ?1 where? c.id=?2")
public int updateComment(String author,Integer id);
}
```
(4)編寫service層
```java
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
public Comment findCommentById(Integer id){
Optional<Comment> comment = commentRepository.findById(id);
if(comment.isPresent()){
Comment comment1 = comment.get();
return comment1;
}
return null;
? ? }
```
(5)編寫Controller層
```java
@RestController
public class CommentController {
@Autowired
private CommentService commentService;
@RequestMapping(value = "/findCommentById")
public Comment findCommentById(Integer id){
Comment comment = commentService.findCommentById(id);
return comment;
}
}
```
(6)編寫配置文件
?? ? ? ?
在項目全局配置文件application.properties中編寫對應的數據庫連接配置?
```properties
? ? ?? #
MySQL數據庫連接配置
? ? ?? spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
? ? ?? spring.datasource.username=root
? ? ?? spring.datasource.password=root
? ? ?? #顯示使用JPA進行數據庫查詢的SQL語句
? ? ?? spring.jpa.show-sql=true
? ? ?? #開啟駝峰命名匹配映射
? ? ?? mybatis.configuration.map-underscore-to-camel-case=true
? ? ?? #解決亂碼
? ? ?? spring.http.encoding.force-response=true
```
(7)測試
圖情況,是因為沒有在Spring Boot項目中開啟緩存管理孵延。在沒有緩存管理的情況下吕漂,雖然數據表中的數據沒有發(fā)生變化,但是每執(zhí)行一次查詢操作(本質是執(zhí)行同樣的SQL語句)尘应,都會訪問一次數據庫并執(zhí)行一次SQL語句
***上了拉勾教育的《Java工程師高薪訓練營》惶凝,做一下筆記吼虎。希望拉勾能給我推到想去的公司,目標:字節(jié)2韵省思灰!***