SpringBoot基礎回顧-14

Spring Boot繼承了Spring框架的緩存管理功能,經過使用@EnableCaching註解開啓基於註解的緩存支持,Spring Boot就能夠啓動緩存管理的自動化配置。java

接下來針對Spring Boot支持的默認緩存管理進行講解mysql

#### **5.1.1** 基礎環境搭建spring

**1.準備數據**sql

使用建立的springbootdata的數據庫,該數據庫有兩個表t_article和t_comment數據庫

**2.建立項目,功能編寫**緩存

(1)在Dependencies依賴選擇項中添加SQL模塊中的JPA依賴、MySQL依賴和Web模塊中的Web依賴 springboot

(2)編寫數據庫表對應的實體類,並使用JPA相關注解配置映射關係 mybatis

```javaapp

      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項目中開啓緩存管理。在沒有緩存管理的狀況下,雖然數據表中的數據沒有發生變化,可是每執行一次查詢操做(本質是執行一樣的SQL語句),都會訪問一次數據庫並執行一次SQL語句


\*上了拉勾教育的《Java工程師高薪訓練營》,作一下筆記。但願拉勾能給我推到想去的公司,目標:字節!!\**

相關文章
相關標籤/搜索